在 __init__ 中设置属性

我想B从A并使用__init__from创建一个子类,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>

不评估该属性。


我怎样才能正确地做到这一点,而无需手动复制__init__从A?


万千封印
浏览 200回答 1
1回答

回首忆惘然

一种补救方法是也c变成财产A;该属性仅返回(私人)成员self._c:class A:&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; self.a = 1&nbsp; &nbsp; &nbsp; &nbsp; self.b = 1&nbsp; &nbsp; &nbsp; &nbsp; self._c = 1&nbsp; &nbsp; @property&nbsp; &nbsp; def c(self):&nbsp; &nbsp; &nbsp; &nbsp; return self._cclass B(A):&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; super().__init__()&nbsp; # because I want 'a' and 'b', (but not 'c')&nbsp; &nbsp; &nbsp; &nbsp; self._c = 2&nbsp; &nbsp; # is already inherited from A&nbsp; &nbsp; # @property&nbsp; &nbsp; # def c(self):&nbsp; &nbsp; #&nbsp; &nbsp; &nbsp;return self._ca = A()b = B()print(a.c)&nbsp; # 1print(b.c)&nbsp; # 2如果你不能改变A(并假设你的财产的目的是使c只读),这是一个变体:c.setter如果self._c不是,将引发错误None:class A:&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; self.a = 1&nbsp; &nbsp; &nbsp; &nbsp; self.b = 1&nbsp; &nbsp; &nbsp; &nbsp; self.c = 1class B(A):&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; self._c = None&nbsp; &nbsp; &nbsp; &nbsp; super().__init__()&nbsp; # the setter for c will work as self._c = None&nbsp; &nbsp; &nbsp; &nbsp; self._c = 2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# now we set c to the new value&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # (bypassing the setter)&nbsp; &nbsp; @property&nbsp; &nbsp; def c(self):&nbsp; &nbsp; &nbsp; &nbsp; return self._c&nbsp; &nbsp; @c.setter&nbsp; &nbsp; def c(self, value):&nbsp; &nbsp; &nbsp; &nbsp; if self._c is not None:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; raise AttributeError&nbsp; &nbsp; &nbsp; &nbsp; self._c = value
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python