动态变量创建 [英] Dynamic variable creation
本文介绍了动态变量创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的问题是如何即时"创建变量.我正在尝试生成具有一组随机属性的对象.
My question is how to create variables "on the fly". I'm trying to generate an object with a random set of attributes.
from random import randint, choice
class Person(object):
def __init__(self):
self.attributes = []
possible_attributes= ['small', 'black', 'scary', 'smelly', 'happy'] # idk, random
chance = randint(1,5)
chosen_attributes = []
for i in xrange(chance):
#psuedo code...
local_var = choice(possible_attributes)
if local_var not in chosen_attributes:
VAR = local_var # VAR needs to be dynamic and 'global' for use later on
chosen_attributes.append(local_var)
Person.attributes.append(local_var)
我很肯定我想做的事不是一个好方法,因此,如果有人了解我在寻找什么并且可以提供一种更好的方法(一种对初学者有效的方法),我将非常感激
I'm positive how I'm wanting to do this is not a good way, so if anyone understand what I'm looking for and can offer a better method (one that works, for starters) I would be most appreciative.
推荐答案
要将属性添加到类的实例,可以使用 .__ dict __
:
To add attributes to an instance of the class you can use .__dict__
:
class Person(object):
def addattr(self,x,val):
self.__dict__[x]=val
输出:
>>> a=Person()
>>> a.addattr('foo',10)
>>> a.addattr('bar',20)
>>> a.foo
10
>>> a.bar
20
>>> b=Person()
>>> b.addattr('spam','somevalue')
>>> b.spam
'somevalue'
这篇关于动态变量创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文