[英]how to create class variable dynamically in python
我需要制作一堆 class 變量,我想通過循環遍歷這樣的列表來完成:
vars=('tx','ty','tz') #plus plenty more
class Foo():
for v in vars:
setattr(no_idea_what_should_go_here,v,0)
可能嗎? 我不想將它們作為實例(在 __init__ 中使用 self),而是作為 class 變量。
您可以在創建類后立即運行插入代碼:
class Foo():
...
vars=('tx', 'ty', 'tz') # plus plenty more
for v in vars:
setattr(Foo, v, 0)
此外,您可以在創建類時動態存儲變量:
class Bar:
locals()['tx'] = 'texas'
如果由於任何原因您不能使用 Raymond 在類創建后設置它們的答案,那么也許您可以使用元類:
class MetaFoo(type):
def __new__(mcs, classname, bases, dictionary):
for name in dictionary.get('_extra_vars', ()):
dictionary[name] = 0
return type.__new__(mcs, classname, bases, dictionary)
class Foo(): # For python 3.x use 'class Foo(metaclass=MetaFoo):'
__metaclass__=MetaFoo # For Python 2.x only
_extra_vars = 'tx ty tz'.split()
遲到了,但使用type
類構造函數!
Foo = type("Foo", (), {k: 0 for k in ("tx", "ty", "tz")})
locals()
版本在課堂上對我不起作用。
以下可用於動態創建類的屬性:
class namePerson:
def __init__(self, value):
exec("self.{} = '{}'".format("name", value)
me = namePerson(value='my name')
me.name # returns 'my name'
setattr(object, name, value)
這是getattr()
的對應物。 arguments 是一個 object,一個字符串和一個任意值。 該字符串可以命名現有屬性或新屬性。 function 將值分配給屬性,前提是 object 允許。 例如, setattr(x, 'name', value)
等價於x.name = value
。
您需要的function是:
setattr(obj, name, value)
這允許您為給定的 class 設置命名屬性(這可以是self
)。
這個 function 的內置文檔非常不言自明:
Signature: setattr(obj, name, value, /)
Docstring:
Sets the named attribute on the given object to the specified value.
setattr(x, 'y', v) is equivalent to ``x.y = v''
Type: builtin_function_or_method
使用示例
它的一個用途是使用字典來設置多個 class 屬性,在我的例子中,這是來自xpath定義。 我覺得通過將可能更脆弱的 xpath 定義全部放在一個地方來提高可維護性:
class Person:
def _extract_fields(self):
''' Process the page using XPath definitions '''
logging.debug("_extract_fields(): {}".format(repr(self)))
# describe how to extract data from the publicly available site
# (kept together for maintainability)
fields = {
'staff_name':
'//div[@id="staff_name"]//text()',
'staff_dob':
'(//div[@id="staff_dob"]//text())[1]'
}
# populate named class attributes from the dict
for key in fields:
setattr(self, key, self._parsed_content.xpath(fields[key]))
def __init__(self):
self._extract_fields()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.