0

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>
Dillon Miller
  • 763
  • 1
  • 6
  • 18

2 Answers2

1

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()
zvone
  • 18,045
  • 3
  • 49
  • 77
0

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

Rusty Widebottom
  • 985
  • 2
  • 5
  • 14