[英]setting a property in __init__
我想创建一个子类B
从A
并使用__init__
从A
,因为它是相同的长达一个属性/属性。
以下代码显示了我想做的事情
class A:
def __init__(self):
self.a = 1
self.b = 1
self.c = 1
class B(A):
def __init__(self):
super().__init__() # because I want 'a' and 'b', (but not 'c')
@property
def c(self):
return 2
B()
追溯:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-9-95c544214e48> in <module>()
13 return 2
14
---> 15 B()
<ipython-input-9-95c544214e48> in __init__(self)
7 class B(A):
8 def __init__(self):
----> 9 super().__init__() # because I want 'a' and 'b', (but not 'c')
10
11 @property
<ipython-input-9-95c544214e48> in __init__(self)
3 self.a = 1
4 self.b = 1
----> 5 self.c = 1
6
7 class B(A):
AttributeError: can't set attribute
我以为我可以通过做来解决这个问题
class B(A):
def __init__(self):
super().__init__() # because I want 'a' and 'b', (but not 'c')
self.c = property(lambda s: 2)
但是,当然后调用:
>>> B().c
<property at 0x116f5d7c8>
不评估该属性。
如何在不从A
手动复制__init__
情况下正确执行此操作?
一种补救方法是将c
变成A
的属性; 该属性仅返回(私有)成员self._c
:
class A:
def __init__(self):
self.a = 1
self.b = 1
self._c = 1
@property
def c(self):
return self._c
class B(A):
def __init__(self):
super().__init__() # because I want 'a' and 'b', (but not 'c')
self._c = 2
# is already inherited from A
# @property
# def c(self):
# return self._c
a = A()
b = B()
print(a.c) # 1
print(b.c) # 2
如果你不能改变A
(并假设你的财产的目的是使c
只读),这是一个变量:在c.setter
会引发错误,如果self._c
不是None
:
class A:
def __init__(self):
self.a = 1
self.b = 1
self.c = 1
class B(A):
def __init__(self):
self._c = None
super().__init__() # the setter for c will work as self._c = None
self._c = 2 # now we set c to the new value
# (bypassing the setter)
@property
def c(self):
return self._c
@c.setter
def c(self, value):
if self._c is not None:
raise AttributeError
self._c = value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.