In the example below of class syntax, the class in parantheses indicate the clsaas from which the new class inherits - in the current case it’s object.
class Person(object):
"""Person class"""
def __init__(self, name, phone, gender):
self.name = name
self.phone = phone
self.gender = gender
def description(self):
print "Name: %s, phone: %s, gender %s" % (self.name, self.phone, self.gender)
def is_male(self):
if self.gender == 'male':
return True
else:
return False
def is_female(self):
if self.gender == 'female':
return True
else:
return False
person = Person("John", "+011111xxxx", "male");
# output: Name: John, phone: +011111xxxx, gender: male
person.description();
# output: True
print person.is_male();
### Class scope example
Notice how variable is_alive will be available to all the members of the Animal class:
class Animal(object):
is_alive = True
def __init__(self, name):
self.name = name
zebra = Animal("Jeffrey")
giraffe = Animal("Bruce")
panda = Animal("Tach")
print zebra.name, zebra.is_alive
print giraffe.name, giraffe.is_alive
print panda.name, panda.is_alive
# output: Jeffrey True
# output: Bruce True
# output: Tach True
In the example below we have defined a class called Person which inherits from the object, and a class called Student, which inherits the Person.
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def description(self):
print self.name, self.age
class Student(Person):
def __init__(self, name, age, studentId):
self.studentId = studentId
return Person.__init__(self, name, age)
def info(self):
print "Student id number is: %s" % (self.studentId)
student = Student("Tom Jones", 26, 8928372)
# output: Tom Jones 26
student.description()
# output: Student id number is: 8928372
student.info()
super()
At any point in time you can access the parent / superclass of the current class by using super function:
class A(object):
def test(self):
print "This is the parent function"
class B(A):
def test(self):
print "This is the overridden function in the child"
def parent_test(self):
super(B, self).test()
# instantiating from the child class B
instance = B()
# accessing the test function
# output: This is the overridden function in the child
instance.test();
# accessing the parent function using super()
# output: This is the parent function
super(B, instance).test()
# accessing the parent function using parent_test, which is using super()
# output: This is the parent function
instance.parent_test()
__repr__
and print
methods:class Point3D(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return "(%d, %d, %d)" % (self.x, self.y, self.z)
my_point = Point3D(1, 2, 3)
# will use __repr__ function of the class
# output: (1, 2, 3)
print my_point.