[Python] Using @property to clone attributes initialized from superclass

Discussão em 'Python' iniciado por Stack, Outubro 24, 2024.

  1. Stack

    Stack Membro Participativo

    I want to create a class inheriting from a superclass that keeps track of the already initialized class attributes in the superclass. The @property decorator caught my eye and I tried to implement it (see example below).

    class MyClass():

    def __init__(self):
    self.data = 'myinitialdata'

    class MySubClass(MyClass):

    def __init__(self, myclass):
    super().__init__()
    self._myclass = myclass

    @property
    def data(self):
    return self._myclass.data

    def main():
    new_myclass = MyClass()
    new_myclass.data = 'mynewdata'
    new_mysubclass = MySubClass(new_myclass)

    print(new_mysubclass.data)

    if __name__=='__main__':
    main()


    However, if I want to create a property of an already initialized attribute (in the superclass) I always receive an error that the attribute cannot be set:

    AttributeError: can't set attribute 'data'


    The code example works if I do not initialize data in MyClass:

    class MyClass():

    def __init__(self):
    # self.data = 'myinitialdata'
    pass

    class MySubClass(MyClass):

    def __init__(self, myclass):
    super().__init__()
    self._myclass = myclass

    @property
    def data(self):
    return self._myclass.data

    def main():
    new_myclass = MyClass()
    new_myclass.data = 'mynewdata'
    new_mysubclass = MySubClass(new_myclass)

    print(new_mysubclass.data)

    if __name__=='__main__':
    main()


    Output:

    mynewdata


    Am I misusing the @property decorator here or am I missing something else in my implementation? Is the @property decorator meant to be used in that kind of scenario?

    I am currently using Python 3.10.9

    Continue reading...

Compartilhe esta Página