@属性 在 python 中继承的装饰器行为

@property decorator behavior with inheritance in python

我正在学习 python @property 装饰器。我被卡住了,无法找到解决方案。我在SO中检查了this and this one,但我的问题是不同的。

在这里,我创建了一个 Base class,其中我使用 @property装饰器。一切都按预期工作。

我想了解 this 的继承行为。

为此,我创建了另一个 class Derived 派生自 Base class。在 Derived class 中,我试图使用 Derived class 成员函数 [=24= 访问 属性 属性函数 fun_name ].

直接使用 Base class 对象 (obj1) 访问 fun_name 属性按预期工作。但是当我使用 Derived class 成员函数 sample_fun 使用 obj2 对象调用相同的行为时,我对这种行为感到困惑。

class Base:
    def __init__(self,name):
        self.name = name
      
    @property
    def fun_name(self):
        print("Entered the getter fun_name")
        return "Getter-> Hello {}".format(self.name)

    @fun_name.setter
    def fun_name(self,str):
        self.name = str
        print("Setter-> Hello {}".format(self.name))

    def fun_name1(self):
        print("Hello from fun_name1 {}".format(self.name))

class Derived(Base):
    def sample_fun(self):
        print("Calling base call fun directly")
        Base.fun_name1(self)
        print("It works")
        print("Calling base attrib directly")
        
        Base.fun_name     #Here Why it is not entering  into the fun_name ?
        

        print("It prints here but not entering into the fun_name")
        
       
obj1 = Base("Joe")
obj1.fun_name
obj1.fun_name = "Jim"
obj1.fun_name

obj2 = Derived("RAJ")
obj2.sample_fun()

控制台输出:

Entered the getter fun_name
Setter-> Hello Jim
Entered the getter fun_name
Calling base call fun directly
Hello from fun_name1 RAJ
It works
Calling base attrib directly
It prints here but not entering into the fun_name

正如您所见,当我使用 Base class 对象 (obj1) 直接访问它时,它进入了函数。

但是 Derived class 成员函数没有发生同样的行为。正好在sample_fun方法中的Base.fun_name处。

我是不是漏掉了一些重要的概念?

@property 添加一个在 属性 访问时触发的实例方法。注意 self 参数。它在 class 上添加了一个 属性 对象。当您访问 class 的实例时,python 将调用该方法并将 class 实例传递给它。

Base.fun_name 是 class 上的实际 属性 对象。如果你这样做 Base().fun_name 它会像你期望的那样工作。如果 Base.fun_name DID 被调用,它会抛出异常,因为没有 self 可以通过。

@Paul Becotte 已经为我提出的问题提供了很好的解决方案。我找到了另一种方法(无论如何已经存在)来访问我在这里需要的相同功能。因为 Derived class 已经从 Base class 派生而来。因此 Base class 的所有属性都可用于 Derived class。所以我的问题是,如何使用 Derived class 成员函数 sample_fun.

访问 属性 属性函数 fun_name

我最初的想法是这样调用:

Base.fun_name  #This was wrong and Paul already gave an explanation on this

@Paul 的建议是:

Base("ANY NAME").fun_name  #This worked and explanation to this also he had given

我的另一个解决方案(使用 self 调用,因为它派生自 Base):

self.fun_name #This solution also worked since the Derived class is derived from Base

非常感谢!