python私有属性和property装饰器_python – 在使用@property装饰器时在属性的s...

尝试覆盖子类中的属性时,我对此行为有点困惑.

第一个示例设置两个类,Parent和Child. Parent继承自object,而Child继承自Parent.属性a使用属性装饰器定义.调用child.a的setter方法时,会引发AttributeError.

在第二个例子中,通过使用property()函数而不是装饰器,一切都按预期工作.

谁能解释为什么行为不同?此外,是的,我知道不需要Child中的__init__定义.

示例1 – 使用@property

class Parent(object):

def __init__(self):

self._a = 'a'

@property

def a(self):

return self._a

@a.setter

def a(self, val):

self._a = val

class Child(Parent):

def __init__(self):

super(Child, self).__init__()

@property

def a(self):

return super(Child, self).a

@a.setter

def a(self, val):

val += 'Child'

super(Child, self).a = val

p = Parent()

c = Child()

print p.a, c.a

p.a = 'b'

c.a = 'b'

print p.a, c.a

示例1 return – 引发属性错误

a a

Traceback (most recent call last):

File "testsuper.py", line 26, in

c.a = 'b'

File "testsuper.py", line 20, in a

super(Child, self).a = val

AttributeError: 'super' object has no attribute 'a'

示例2 – 使用property()

class Parent(object):

def __init__(self):

self._a = 'a'

def _get_a(self):

return self._a

def _set_a(self, val):

self._a = val

a = property(_get_a, _set_a)

class Child(Parent):

def __init__(self):

super(Child, self).__init__()

def _get_a(self):

return super(Child, self)._get_a()

def _set_a(self, val):

val = val+'Child'

super(Child, self)._set_a(val)

a = property(_get_a, _set_a)

p = Parent()

c = Child()

print p.a, c.a

p.a = 'b'

c.a = 'b'

print p.a, c.a

示例2返回 – 正确工作

a a

b bChild

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值