标签:call() 默认 foo 类的方法 anim ict 类继承 空间 div
class Animal: def __init__(self, name): self.name = name def eat(self): print(‘%s吃‘ % self.name) def drink(self): print(‘%s喝‘ % self.name) def pull(self): print(‘%s拉‘ % self.name) def sow(self): print(‘%s撒‘ % self.name) def sleep(self): print(‘%s睡‘ % self.name) class Cat(Animal): def call(self): print(‘喵喵叫‘) class Dog(Animal): def call(self): print(‘汪汪叫‘) class Chook: def call(self): print(‘大爷,来玩呀....‘) cat1 = Cat(‘阿花‘) cat1.eat() cat1.drink() chook1 = Chook() chook1.call() 继承:子类继承父类的一切. class Cat(Animal) Animal 叫做父类,也叫作基类. Cat 叫做子类,也叫作派生类.
class Animal: nickname = ‘动物‘ def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex def eat(self): print("%s在吃东西" % self.name) class Person(Animal): pass class Dog(Animal): pass class Cat(Animal): pass p1 = Person(‘太白‘,25,‘男‘) p1.eat() dog1 = Dog(‘日天‘,6,‘公‘) dog1.eat() print(p1.nickname)
print(Person.nickname)
# 继承最大的特点节省代码.与其他类发生关联.
# 为什么子类能找到父类的所有?? 存在父类指针的概念
# 类名,对象都可以找到父类的所有方法.
#python3x python2x
#python3x 类默认都继承object,继承object类的类叫做新式类.
#python2x 类默认什么不都继承,不继承object的类叫做经典类.如果在python2x中,你让他继承object类,就变成新式类了.
#继承去分:
# 单继承,多继承.
#单继承: 查询顺序一直向上(新式类,经典类一样.)
# class Animal: # nickname = ‘动物‘ # # def __init__(self, name, age, sex): # self.name = name # self.age = age # self.sex = sex # # def eat(self): # print("%s在吃东西" % self.name) # # # class Person(Animal): # # def speek(self): # print(‘%s可以用语言交流‘ % self.name) # # # class Brid(Animal): # # def __init__(self, name, age, sex, wing): # self = b1 对象空间 # # Animal.__init__(self,name,age,sex) # 第一种 如何在子类中执行父类方法 # super(Brid,self).__init__(name, age, sex) # 第二种 如何在子类中执行父类方法 # self.wing = wing # # def eat(self, food): # super().eat() # print(‘%s吃%s‘ % (self.name, food)) # # def bite(self): # print(‘%s可以啄人‘ % self.name) # p1 = Person(‘太白‘,25,‘男‘) # print(p1.nickname) b1 = Brid(‘鹦鹉‘, 12, ‘母‘, ‘大翅膀‘) b1.eat(‘小米‘) # print(b1.__dict__) # b1.eat(‘小米‘) # def func1(y,z,w): # print(666) # def func(x,y,z,w): # func1(y,z,w) # func(1,2,3,4) # 在子类中,执行父类的方法 # Animal.__init__(self,name,age,sex) # 第一种 #用这种: super().__init__(name, age, sex) # 第二种 完整的写法 super(Brid,self).__init__(name, age, sex) 不提倡
# 多继承: # 新式类 : 广度优先 # class A: # def func(self): # print(‘A‘) # # class B(A): # # def func(self): # print(‘B‘) # # class C(A): # def func(self): # print(‘C‘) # # class D(B): # def func(self): # print(‘D‘) # class E(C): # def func(self): # print(‘E‘) # # class F(D,E): # def func(self): # print(‘F‘) # # d = F() # d.func() # print(F.mro()) # F.mro()可以查看继承执行顺序
# 经典类 : 深度优先 # class A: # def func(self): # print(‘A‘) # # class B(A): # # def func(self): # print(‘B‘) # class C(A): # def func(self): # print(‘C‘) # class D(B,C): # # def func(self): # print(‘D‘) # # d = D() # d.func()
标签:call() 默认 foo 类的方法 anim ict 类继承 空间 div
原文地址:https://www.cnblogs.com/molieren/p/9249464.html