如何解决在蟒蛇?为什么子类继承父类?当您使用 init of 方法分配父级时?但它不起作用
class Person:
@property
def name(self):
return self.__name
@name.setter
def name(self,name):
self.__name = name
@property
def age(self):
return self.__age
@age.setter
def age(self,age):
self.__age = age
def __init__(self,name,age):
self.__name = name
self.__age = age
pass
def print_info(self):
print("my name is {} and my age is {}".format(self.__name,self.__age))
pass
class Student(Person):
@property
def school_name(self):
return self.__school_name
@school_name.setter
def school_name(self,school_name):
return self.__school_name
def __init__(self,school_name,age):
Person.__init__(self,age)
self.__school_name = school_name
pass
def print_info(self):
print("my schoolname is {} name is {} age is {}".format(self.__school_name,self.__name,self.__age))
print("hello")
pass
if __name__ == '__main__':
stu = Student("primary school","songpengfei",22)
stu.print_info()
pass
Traceback (most recent call last):
File "<input>",line 1,in <module>
File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_umd.py",line 198,in runfile
pydev_imports.execfile(filename,global_vars,local_vars) # execute the script
File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py",line 18,in execfile
exec(compile(contents+"\n",file,'exec'),glob,loc)
File "/Users/songpengfei/PycharmProjects/untitled1/review.py",line 69,in <module>
stu.print_info()
File "/Users/songpengfei/PycharmProjects/untitled1/review.py",line 60,in print_info
print("my schoolname is {} name is {} age is {}".format(self.__school_name,self.__age))
AttributeError: 'Student' object has no attribute '_Student__name'
解决方法
简短的回答是您应该使用属性 self.name
而不是字段 self.__name
。同样,您应该只在 __
中使用以 @property
开头的名称。否则使用该属性。因此,例如,在 self.age
之外使用 self.__age
而不是 @property
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。