问题描述
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
。