簡體   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