繁体   English   中英

Python 访问类似名称的 class 和实例属性

[英]Python accessing similarly named class and instance attributes

我有一个 class 与 class 和具有相同名称的实例属性。 有没有办法根据访问的上下文返回他们尊重的价值?

例子:

class A:
    b = 'test'
    @property
    def b(self):
        return 'not test'

期望的结果:

>>> A().b
'not test'
>>> A.b
'test'

实际结果:

>>> A().b
'not test'
>>> A.b
<property object at 0x03ADC640>

我不知道你为什么想要那个,但这会起作用:

class ClassWithB(type):
    @property
    def b(self):
        return 'test'


class A(metaclass=ClassWithB):
    @property
    def b(self):
        return 'not test'

它的行为如下:

>>> A.b
'test'
>>> A().b
'not test'

您还可以使用例如描述符

class B:
    def __get__(self, obj, type_=None):
        if obj is None:
            return 'test'
        else:
            return 'not test'

class A:
    b = B()

否 - 该方法会隐藏实例 - 有关更多信息,请参阅此https://stackoverflow.com/a/12949375/13085236

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM