作者tytyty (tytyty)
看板Python
标题Re: [问题] property override的困扰
时间Wed Aug 19 14:34:47 2015
※ 引述《kentyeh (kent)》之铭言:
: 最近在学习Python,碰到 setter 与 getter override的困扰
: 首先以下是 Parent 的设定
: class Parent():
: @property
: def foo(self):
: return self._bar
: @foo.setter
: def foo(self, foo):
: self._bar = foo
: 然後是继承者Child
: class Child(Parent):
: def getFoo(self):
: return "Overrides:"+super().foo
: def setFoo(self, foo):
: self._bar = ' '.join(['Child\'s foo:', foo])
: foo=property(getFoo,setFoo)
: 用以下程式测试
: child = Child()
: child.foo="Hello World"
: print(child.foo)
: 取得预期的结果:
: Overrides:Child's foo: Hello World
: 以下只Override setter
: class Child(Parent):
: @Parent.foo.setter
: def foo(self, foo):
: self._bar = ' '.join(['Child\'s foo:', foo])
: 或是只Override getter
: class Child(Parent):
: @Parent.foo.getter
: def foo(self):
: return "Override getter:"+self._bar
: 也都可以得到预期的结果
: 但是组合起来後
: class Child(Parent):
: @Parent.foo.getter
: def foo(self):
: return "Override getter:"+self._bar
: @Parent.foo.setter
: def foo(self, foo):
: self._bar = ' '.join(['Child\'s foo:', foo])
: 却只得到
: Child's foo: Hello World
: 有先进可以解惑吗?
首先来个线上跑扣页面
http://goo.gl/0G1JFE
重点已经注解在扣里面了,搭配测试结果应该很容易了解。
其实需要知道的只是 decorator 不过是一种 syntactic sugar,下面这两段扣
意思是一样的。
#1
@property
def foo(self):
return self._foo
#2
def foo(self):
return self._foo
foo = property(foo)
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 98.234.217.60
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1439966089.A.3D4.html
1F:推 kentyeh: 辛苦了,但仍不理解为什麽但Child2的setter置换後会连同 08/19 17:23
2F:→ kentyeh: getter一起换掉,而Child1却不会? 08/19 17:24
3F:→ tytyty: 因为decorator的来源不一样,Child1的setter用的是Parent 08/19 23:52
4F:→ tytyty: 里的foo property,Child2当要decorate setter时把自己的 08/19 23:53
5F:→ tytyty: foo property拿来用,所以不会把置换过的getter丢掉。 08/19 23:54