class Animal(object): def eat(self): print("动物会吃") class Cat(Animal): def eat(self): print("猫吃鱼") class Dog(Animal): def eat(self): print("狗吃骨头") class Person(object): def eat(self): print("人吃五谷杂粮") def func(creature): creature.eat()
-- we can override the function of the parent function to create a new class
class A(object): pass class B(object): pass class C(A, B): def __init__(self, name, age): self.name = name self.age = age x = C('gdc', 20) if __name__ == '__main__': # __dict__ 显示 实例 和 方法 的情况 print(x.__dict__) print(C.__dict__) print('_____________________________') # 输出对象所属的类 print(x.__class__) print(C.__bases__) # return the tuple of the parent class print(C.__base__) # return the basic parent class print(C.__mro__) print(A.__subclasses__()) # return the list of the subclasses print('_____________________________')
-- 可以使用不同方法得到类的不同信息
class Student: def __init__(self, name, age): self.name = name self.age = age # override the __add__() can add two classes def __add__(self, other): return self.age + other.age def __len__(self): return len(self.name) stu1 = Student('1', 20) stu2 = Student('gdc', 20) if __name__ == '__main__': print(stu1 + stu2) print('__________________________') print(stu2.__len__())
--通过重写add和len方法来实现运算重载的效果