对象、类
类就像一套印钱的模具,对象就是用这套模具印出来的钞票。
类的关系---继承
就像儿子继承父亲的家产,儿子可以少奋斗10年。子类继承父类後,可以获得父类的属性和方法,子类可以省去重复部分代码。
教材举例
class Animal(object):
pass
class Dog(Animal):
def __init__(self, name):
print "Dog class init"
self.name = name
class Cat(Animal):
def __init__(self, name):
print "Cat class init"
self.name = name
class Person(object):
def __init__(self, name):
print "Person class init"
print "person super"
self.name = name
self.pet = None
class Employee(Person):
def __init__(self, name, salary):
print "Employee class init"
super(Employee, self).__init__(name)
self.salary = salary
class Fish(object):
pass
class Salmon(Fish):
pass
class Halibut(Fish):
pass
rover = Dog("Rover")
satan = Cat("Satan")
mary = Person("Mary")
mary.pet = satan
frank = Employee("Frank", 120000)
frank.pet = rover
flipper = Fish()
crouse = Salmon()
harry = Halibut()
这段代码定义了8个类,包括
-动物类(Animal)
----猫类(Cat)
----狗类(Dog)
-人类(Person)
----职员类(Employee)
-鱼类(Fish)
----三文鱼类(Salmon)
----大比目鱼类(Halibut)
这里的父类子类在现实中也是有意义的,比如猫和狗都属于动物,职员是一个人,三文鱼和比目鱼都是鱼。
init是类的初始化方法,在实例化时(用模板印钞票时)会自动调用这个构造函数。
注意Employee类的构造函数中有一句代码“super(Employee, self).init(name)”
super(type[, object-or-type])
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.
super是一个类,“super(Employee, self)”调用了super的初始化方法,返回一个能调用父类或兄弟类的代理对象,用于访问在一个类中被重写的继承方法非常有用。可以参考一下链接了解。
网友评论