Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python subclass that doesn't inherit attributes

I'd like to create an Python class that superficially appears to be a subclass of another class, but doesn't actually inherit its attributes.

For instance, if my class is named B, I'd like isinstance(B(), A) to return True, as well as issubclass(B, A), but I don't want B to have the attributes defined for A. Is this possible?

Note: I don't control the implementation of A.

Why I care: The module I'm working with checks that a passed object is a subclass of A. I want to define the necessary attributes in B without inheriting the superfluous attributes defined in A (whose implementation I do not control) because I'm using __getattr__ to pass some attribute calls onto a wrapped class, and if these attributes are defined by inheritance from A, __getattr__ won't be called.

like image 826
Luke Taylor Avatar asked Mar 24 '26 11:03

Luke Taylor


2 Answers

In Python3, override the special method __getattribute__. This gives you almost complete control over attribute lookups. There are a few corner cases so check the docs carefully (it's section 3.3.2 of the Language Reference Manual).

like image 195
Paul Cornelius Avatar answered Mar 27 '26 01:03

Paul Cornelius


You could implement __getattribute__ to raise AttributeErrors for the attributes that are not in B:

class A(object):
    def __init__(self):
        self.foo = 1

    def bar(self):
        pass

class B(A):
    def __init__(self):
        self.baz = 42

    def __getattribute__(self, attr):
        if attr in ('foo', 'bar'):
            raise AttributeError()
        return super(B, self).__getattribute__(attr)

I'm curious, why would you do this?

like image 43
λuser Avatar answered Mar 26 '26 23:03

λuser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!