简体   繁体   English

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

[英]Python accessing similarly named class and instance attributes

I have a class with class and instance attributes with the same name.我有一个 class 与 class 和具有相同名称的实例属性。 Is there a way to return their respected value based on the context they are accessed?有没有办法根据访问的上下文返回他们尊重的价值?

Example:例子:

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

Desired Results:期望的结果:

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

Actual Results:实际结果:

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

I have no idea why you want that, but this would work:我不知道你为什么想要那个,但这会起作用:

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


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

It behaves like this:它的行为如下:

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

You could also use eg a descriptor :您还可以使用例如描述符

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

class A:
    b = B()

No - the method shadows the instance - see this for more information https://stackoverflow.com/a/12949375/13085236否 - 该方法会隐藏实例 - 有关更多信息,请参阅此https://stackoverflow.com/a/12949375/13085236

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

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