class Employee:
def __init__(self, name):
self.name = name
def getName(self):
return self.name
@property
def getNameAgain(self):
return self.name
person = Employee("John")
print(person.getName()) #John <--(calling method)
print(person.name) #John <--(using @property)
Run Code Online (Sandbox Code Playgroud)
所以我使用 getName() 得到了相同的结果,那么为什么我们要在 getNameAgain() 中使用 @property 装饰器呢?我可以知道什么更好/建议使用吗?先感谢您!
对于这个例子,我是否总是需要实例化父类,因为当我删除它时它仍然有效?
class Person:
def __init__(self, name):
self.name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
class SubPerson(Person):
# Do I need this an init call? If I remove this init call, it still runs
def __init__(self, name):
super().__init__(name)
@property
def name(self):
return super().name
@name.setter
def name(self, value):
return super(SubPerson, SubPerson).name.__set__(self, value)
s = SubPerson("John")
print(s.name) //John
Run Code Online (Sandbox Code Playgroud)
谢谢你!