class basicClass(): var1 = "bacon" var2 = "sausage" var3 = "toast" breakfast = basicClass() print breakfast.var1This will output:
"bacon"The class is defined first with all the variables we want in it. We then use that class or blueprint to create an object, breakfast, and by referencing that object followed by a dot and the attribute (much like importing modules) we can access the data from the class.
Classes can inherit attributes from other classes.
class basicClass(): var1 = "bacon" var2 = "sausage" var3 = "toast" class subClass(basicClass): pass breakfast = subClass() print breakfast.var2Will output:
"sausage"The new "subclass" has inherited all attributes of the class that was passed in its parameters. This is why the subclass can contain no data and we are still able to call it and return values from variables.
On top of this when creating a class that will inherit from another, you can overwrite any attribute you need to at the time of creation.
class basicClass(): var1 = "bacon" var2 = "sausage" var3 = "toast" class subClass(basicClass): var2 = "hash browns" breakfast = subClass() print breakfast.var2Will output:
"hash browns"The value of var2 was overwritten by the child class.
No comments:
Post a Comment