小编She*_*hee的帖子

当我可以使用普通的方法 getter 时,为什么还要使用 @property 装饰器?

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 装饰器呢?我可以知道什么更好/建议使用吗?先感谢您!

python oop properties decorator

7
推荐指数
1
解决办法
5667
查看次数

当代码仍然运行时,我是否需要始终需要在子类中使用 init 来实例化父类?

对于这个例子,我是否总是需要实例化父类,因为当我删除它时它仍然有效?

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)

谢谢你!

python oop inheritance init super

7
推荐指数
1
解决办法
1836
查看次数

标签 统计

oop ×2

python ×2

decorator ×1

inheritance ×1

init ×1

properties ×1

super ×1