簡體   English   中英

在 __init__ 中設置屬性

[英]setting a property in __init__

我想創建一個子類BA並使用__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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM