更改类的属性不会触发setter,打印它也不会触发getter

6qfn3psc  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(422)

我可能错过了一些非常简单的东西。
我想用 property() 将getter和setter函数添加到 MyClass .

class MyClass:
    def __init__(self, attr):
        self._attr = attr

        def attr_setter(self, value):
            print(f'Setting attr')
            self._attr = value

        def attr_getter(self):
            print('Getting attr')
            return self._attr

        self.attr = property(fget=attr_getter, fset=attr_setter)

c = MyClass('something')
print(c.attr)
c.attr = 'something else'
print(c.attr)

但是,不会触发打印语句和赋值 attr_setterattr_getter . 我得到以下输出:
位于<0x0000024a26b489a0>的属性对象
别的

5f0d552i

5f0d552i1#

在评论中查找详细信息

class MyClass:
    def __init__(self, attr):
        #self._attr = attr --> you might want to call the setter
        self.attr_setter(attr)

    # correcting the indentation
    def attr_setter(self, value):
        print(f'Setting attr')
        self._attr = value

    def attr_getter(self):
        print('Getting attr')
        return self._attr

    attr = property(fget=attr_getter, fset=attr_setter)

c = MyClass('something')  #Setting attr
print(c.attr) #Getting attr something
c.attr = 'something else' #Setting attr
print(c.attr) #Getting attr something else

# Setting attr

# Getting attr

# something

# Setting attr

# Getting attr

# something else

相关问题