简体   繁体   中英

Python overriding setter to an attribute with no setter?

I have a class A made by someone else, that I cannot edit:

class A:
    def __init__(self, x):
        self.x = x

Now I'm trying to inherit my own class B from A , and have x as a property instead of an attribute. Is this possible?

I already tried:

class B(A):
    def __init__(self, x):
        super().__init__(x)

    @property
    def x(self):
        return super().x

    @x.setter
    def x(self, x):
        super().x = x
        print(x)  # my stuff goes here

But as I expected, it's not possible: AttributeError: 'super' object has no attribute 'x'

Is there any other method, some workaroud maybe?

No, you cannot use super() for anything other than class attributes; x is an instance attribute, and there is no inheritance mechanism for attributes.

Instance attributes live in a single namespace; there is no 'parent instance' attribute namespace.

You can still reach the attribute in the instance __dict__ object:

class B(A):
    @property
    def x(self):
        return self.__dict__['x']

    @x.setter
    def x(self, x):
        self.__dict__['x'] = x
        print(x)  # my stuff goes here

A property is a data descriptor , meaning that it is looked up before the instance attributes are consulted (see the descriptor howto ), but you can still access it directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM