如有帮助,望采纳。点击我回答右上角【采纳】按钮
class Person:
def __init__(self, name, age):
self.name = name
self.__age = age
print('父类的构造方法被调用')
@property
def age(self):
return self.__age
@age.setter
def age(self, age):
self.__age = age
# 成员方法
def show(self):
print("父类的show")
class Worker(Person):
def __init__(self,name,age,num):
# 在子类的构造函数中调用父类的构造方法
# 方式一:
super().__init__(name, age)
print('子类的构造函数被调用了')
self.num = num
# # 方式二:
# Person.__init__(name,age)
class Doctor(Person):
def __init__(self, name, age, num):
super().__init__(name, age)
self.num = num
def show(self):
print("Doctor show")
p1 = Person('Tom', 23)
p1.show() # >> 父类的show
print(p1.age)
# 创建子类对象
w1 = Worker('Jack', 21, 2)
# 子类对象可以调用父类对象中未被私有化的方法
w1.show() # >>父类的show
#子类访问父类私有属性,只需要父类中提供@property装饰的方法【get和set方法】
print(w1.age)
print(p1.name) #>> tom
d1 = Doctor("lili", 26, 2)
d1.show() #>>Doctor show
print(d1.name)
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632