Dillon Miller
Dillon Miller

Reputation: 1123

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>

Upvotes: 0

Views: 116

Answers (2)

zvone
zvone

Reputation: 19402

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 e.g. a descriptor:

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

class A:
    b = B()

Upvotes: 1

Rusty Widebottom
Rusty Widebottom

Reputation: 984

No - the method shadows the instance - see this for more information https://stackoverflow.com/a/12949375/13085236

Upvotes: 0

Related Questions