A class in python is a blueprint of the instances which you can create from, for example i want to create a house and i have the description and the properties of that house, now I can spawn multiple houses using that blueprint and every instance will be a separate entity from the other but identical in properties defined in the blueprint i.e class
So we create a class house and for example will create three functions i.e one to name the house, location and third to print the properties of that house. Below is a simple class definition, you might be wondering what the hell this “self” is, well basically its a temporary place holder for the object which is created from this class, this helps the class to identify the object and its attributes within the class, in this case its the “first” and “second” object.
1 2 3 4 5 6 7 8 9 10
| >>> class house:
... def houseName(self,name):
... self.name = name
... def houseLocation(self,location):
... self.location = location
... def printName(self):
... print "House name: %s " % self.name
... print "Location: %s " % self.location
...
>>> |
The next four steps creates the “first” object from the class “house()” sets the name, location and prints it.
1 2 3 4 5 6 7
| >>>
>>> first = house()
>>> first.houseName = "Dog Villa"
>>> first.houseLocation = "Zetland Street"
>>> first.printName()
House name: Dog Villa
Location: Zetland Street |
we use the same methods to create the second object “second”
1 2 3 4 5 6
| >>> second = house()
>>> second.houseName('Cat street')
>>> second.houseLocation('Sherwood Way')
>>> second.printName()
House name: Cat street
Location: Sherwood Way |
Next we will create a parent class and inherit it on a subclass, also see how we can manipulate the inherited variables from the parent class, Note here “pass” in the childClass means “dont do anything”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| >>> class parentClass:
... var1="i am var1"
... var2 ="i am var2"
...
>>> class childClass(parentClass):
... pass
...
>>> parentObject=parentClass()
>>> parentObject.var1
'i am var1'
>>> parentObject.var2
'i am var2'
>>> childObject=childClass()
>>> childObject.var1
'i am var1'
>>> childObject.var2
'i am var2'
>>> |
Continue Reading…