Python:将元素附加到类的列表中
我有一节课看起来像这样Python:将元素附加到类的列表中,python,list,class,attributes,Python,List,Class,Attributes,我有一节课看起来像这样 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(XSh
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()
,这可能是您问题的一个很好的解决方案(有关更多信息,请参阅)。它以什么方式不起作用?您在该行末尾缺少一个括号,这是您的原始代码中的括号吗?谢谢,这看起来正是我需要的。我试试看。但是什么是条件字段()?我找不到太多关于它的信息。