我想用动态创建的属性创建一个对象(比如说foo
)。我可以这样做:
class Foo:
pass
foo.bar = 42
...
print(foo.bar) # 42
但是,当我创建属性时,我还不知道该属性的名称。我需要的是这样的事情:
def createFoo(attributeName):
foo = ???
??? = 42
...
foo = createFoo("bar")
print(foo.bar) # 42
我怎样才能做到这一点?
答案 0 :(得分:1)
foo = Foo()
foo.__dict__['man'] = 3.14
print(foo.man) # 3.14
或者,正如我最初在shmee建议setattr之前回答的那样:
tell application "Terminal"
if not (exists window 1) then reopen
activate
do script "subl ~/vagrant-lamp/sites/codeup.dev/public/" in window 1
do script "cd ~/vagrant-lamp/; vagrant up" in window 1
end tell
答案 1 :(得分:0)
你可以使用字典
然后创建一个get函数来轻松访问它
def createFoo(attributeName):
dict[attributeName] = 42;
def GetVal(attributeName)
return dict[attributeName];
...
foo = createFoo("bar")
print(foo.GetVal("bar")) # 42