Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if class attribute was defined or derived in given class

Example

class A:
    foo = 1

class B:
    foo = 2

class C:
    foo = 3

class D(A, B, C):
    pass

def collect_foo(cls):
    import inspect
    foos = []
    for c in inspect.getmro(cls):
        if hasattr(c, 'foo'):
            foos.append(c.foo)
    return foos

Now collect_foo(D) returns [1, 1, 2, 3] - 1 is doubled as D derives it from A. The question is - how to get unique foos. First thing which came to my mind was checking if property is derived or declared in given class - is it possible? How to do that?

like image 255
Mikoskay Avatar asked Mar 09 '11 23:03

Mikoskay


1 Answers

Just check

'foo' in c.__dict__

instead of

hasattr(c, 'foo')

This will only yield True if the attribute is defined in c itself.

like image 161
Sven Marnach Avatar answered Oct 13 '22 05:10

Sven Marnach