标签:创建 运行 @class col .com 子类 tin icm src
当要访问私有属性的时候,可以新建一个方法,内部方法是可以调用私有属性的,然后通过调用这个方法来获取私有属性的值:
print(r1.show_status())
如果实例调用变量,实例变量和类变量都定义了相同变量,那么优先去实例变量,没有再找类变量。
class Peolpe(): def __init__(self,name,age): self.name = name self.age = age def talk(self): print("%s is talking..."%self.name) def sleep(self): print("%s is sleeping..."%self.name) class Man(Peolpe): ##此处继承 pass m1 = Man("liyang",22) m1.sleep()
继承重用
class Peolpe(): def __init__(self,name,age): self.name = name self.age = age def talk(self): print("%s is talking..."%self.name) def sleep(self): print("%s is sleeping..."%self.name) class Man(Peolpe): ##此处继承 def eat(self): print("%s is eating"%self.name) def sleep(self): Peolpe.sleep(self) ##此处调用父类方法,如果没有这行,sleep方法会重写,不会执行父类方法 print("man also is sleeping") m1 = Man("liyang",22) m1.sleep()
如果子类要新增初始化参数呢,要修改一下子类
class Man(People): ##此处继承 def __init__(self,name,age,location): People.__init__(self,name,age) ##继承父类初始化参数 self.location = location ##新加一个参数
或者
class Man(People): ##此处继承 def __init__(self,name,age,location): #People.__init__(self,name,age) ##继承父类初始化参数 super(Man,self).__init__(name,age) ##使用super内置函数,新式写法 self.location = location ##新加一个参数
多继承:
# -*- coding:utf-8 -*- # Author:Brownyangyang class People(): def __init__(self,name,age): self.name = name self.age = age def talk(self): print("%s is talking..."%self.name) def sleep(self): print("%s is sleeping..."%self.name) class Relation(object): def make_friends(self,obj): print("%s is makeing friends with %s"%(self.name,obj.name)) ##self.name是People那边继承过来的,obj 是定义的一个实例 class Man(People,Relation): ##此处继承 def __init__(self,name,age,location): #People.__init__(self,name,age) ##继承父类初始化参数 super(Man,self).__init__(name,age) self.location = location ##新加一个参数 def eat(self): print("%s is eating"%self.name) def sleep(self): People.sleep(self) ##此处调用父类方法,如果没有这行,sleep方法会重写,不会执行父类方法 print("man also is sleeping in %s"%self.location) class Woman(People,Relation): def get_birth(self): print("%s is borning the baby"%self.name) m1 = Man("xiaohong",22,"nantong") # m1.sleep() w1 = Woman("xiaoming",32) # w1.get_birth() m1.make_friends(w1)
结果:xiaohong is makeing friends with xiaoming
标签:创建 运行 @class col .com 子类 tin icm src
原文地址:https://www.cnblogs.com/brownyangyang/p/9060207.html