简体   繁体   中英

Python accessing similarly named class and instance attributes

I have a class with class and instance attributes with the same name. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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