簡體   English   中英

如何在 Python 中的類之間創建共享 Class 屬性

[英]How to Create Shared Class Attributes between Classes in Python

我昨天問過這個問題,但是我把我的問題寫得太糟糕了,以至於當我意識到我輸入了什么時,所有的回復都是對另一個我沒有的錯誤措辭問題的解決方案。 對不起上次愚蠢的類型。

我有兩個類,我希望它們能夠共享一個公共列表,而不必將其作為參數傳遞。 我還想創建一個對該列表進行加擾的方法,並且我希望該列表與 Class A 和 Class B 中的新加擾列表相同。

我認為這是 inheritance 的情況,所以我創建了一個父 Class 並將列表設置為 class 屬性並制作了一種方法來打亂,但列表變量現在被視為一個實例,這很奇怪。

class A:
    lst = []
    target = 0

    def generateNewLst(self, randomRange, listSize):
        self.lst = [random.randint(*randomRange) for i in range(listSize)]

class B(A):
    pass

class C(A):
    pass

我繼承的方法工作得很好:

a = B()
a.generateNewLst((0, 10), 3)
a.lst  # => [2,5,7]

但是當我創建另一個 B 時:

b = B()
b.lst  # => [] not shared when I want it to be

這不能用 B 中的 class 屬性來解決,因為這不能解決下面更重要的問題......

c = C()
c.lst  # => [] not shared when I want it to be

TL;DR:我想要一個在兩個類的每個實例之間共享的 Class 屬性。 每次我在其中任何一個實例上運行 generateNewList 時,我都想要 a.lst == b.lst == c.lst。

我應該如何重新組織我的設置以按照我想要的方式工作?

您需要一個 static 變量。 To do so make the method generateNewLst static and let him update the static variable lst and not a member variable lst that would belong to the instance of the class and not to the class itself.

class A:
    lst = []

    @staticmethod
    def generateNewLst(randomRange, listSize):
        A.lst = [random.randint(*randomRange) for i in range(listSize)]

class B(A):
    pass

class C(A):
    pass

然后,一旦您生成了 lst,您將擁有它用於所有類。

a = B()
B.generateNewLst((0, 10), 3)
# the same list is available for all classes
print(A.lst) 
print(B.lst)
print(C.lst)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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