簡體   English   中英

Python:將元素追加到類列表

[英]Python: Appending elements to list of a class

我有一堂課,看起來像這樣

class Someclass(something):
    name = "SomeClass"
    field=[XShortField("Field", 0x1000)]

此類由另一個函數使用,但是在使用該類之前,我想將元素追加到字段中,例如

if option == 0: #nothing is added
   pass 
elif option == 1: #one element is added
   SomeClass.field.append(XShortField("Field"+str(option), 0x2000))
elif option == 2: #two elements are added
#and so on

但是看來我不能那樣做。 有訪問類屬性的特殊方法嗎?

您可能要在這里使用子類:

class Someclass1(Someclass):
    field = Someclass.field + [XShortField("Field"+str(option), 0x2000]

s_class = Someclass
if option == 0: #nothing is added
    pass
elif option == 1: #one element is added
    s_class = Someclass1
elif option == 2: #two elements are added
    [...]
    #and so on

這取決於您的上下文,但是,例如,如果您要為Scapy編寫解剖器,那可能是實現此目的的一個好方法;-)

在Scapy協議的特定情況下,您可以查看ConditionalField() ,它可能是解決問題的好方法(有關更多信息,請參見Scapy源代碼 )。

暫無
暫無

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

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