开发者

How to get an attribute just from the current class and not from possible parent classes?

开发者 https://www.devze.com 2023-01-08 12:09 出处:网络
How to get an attribute just from the cu开发者_Python百科rrent class and not from possible parent classes? If I use getattr it traverses class hierarchy but I would like to get None if attribute is no

How to get an attribute just from the cu开发者_Python百科rrent class and not from possible parent classes? If I use getattr it traverses class hierarchy but I would like to get None if attribute is not defined in the current class (even if it is defined in some parent class).


This is not a 100% proof answer (e.g. it will not work for classes that use __slots__), but it will work in most cases:

>>> class A(object):
...    x = 42
...    y = 43
... 
>>> class B(A):
...    x = 11
... 
>>> b = B()

You can check if the attribute is defined in the class directly like this:

>>> 'x' in b.__class__.__dict__
True
>>> 'y' in b.__class__.__dict__
False

Now to answer your question:

# comment explaining why this unusual check is necessary
if 'attribute' in instance.__class__.__dict__:
    value = instance.attribute
else:
    value = None


You kind of painted yourself into a corner with your own rules. Sounds more like like a design shortcoming than a language or class issue with Python, as the beuty of python is to remove and hide the complexity of class inheritance.

You will likely need to settle for an "alternative" solution like this:

class Parent(object):
    property_on_parent = 'default value'
    @property
    def property_accessor(self):
        return self.property_on_parent

class Child(Parent):
    property_on_child = None
    @property
    def property_accessor(self):
        return self.property_on_child

c = Child()
assert c.property_accessor == None

However, i feel that you are better off rethinking the approach.


Nothing prevents you from "resetting" that attrib in the init setting it to None after you init the super (in Python classes inherited and inheriting are super and sub btw, not parent and child).

Unless that attrib is created elsewhere and its presence isn't guaranteed, only in that case walking up the inheritance tree, at which point you might have some serious design issues going on :)

All that said, these are poor man solutions to the problem, and I agree you might have some design issues to address instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消