Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove attribute from subclass in Python

Is there any way to remove an attribute from a subclass that is present in the parent?

In the following example

class A(object):
    foo = 1
    bar = 2

class B(A):
    pass

# <desired code here>

b = B()
assert hasattr(b, 'bar') == False

Is there any code we can write to make the assertion pass?

like image 884
MRocklin Avatar asked Sep 08 '26 15:09

MRocklin


1 Answers

class A(object):
    foo = 1
    bar = 2


class B(A):
    @property
    def bar(self):
        raise AttributeError


>>> b = B()
>>> b.bar

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    b.bar
  File "<pyshell#15>", line 4, in bar
    raise AttributeError
AttributeError
like image 112
jamylak Avatar answered Sep 11 '26 06:09

jamylak