Python - 动态变量 [英] Python - Dynamic variables

查看:137
本文介绍了Python - 动态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是如何创建变量即时。我试图用一组随机的属性生成一个对象。



$ _ code从随机导入randint,选择

类Person(对象):
def __init__ (self):
self.attributes = []

possible_attributes = ['small','black','scary','smelly','happy']#idk,random
chance = randint(1,5)

selected_attributes = []
在我的xrange(机会):
#psuedo代码...
local_var = choice(possible_attributes)
如果local_var不在selected_attributes中:
VAR = local_var#VAR需要是动态的,'全局'在
以后使用selected_attributes.append(local_var)
Person.attributes.append(local_var)

我是积极的,我想要这样做不是一个好办法,所以如果有人明白我在找什么,可以提供一个更好的方法(一个适用于初学者),我将是最感激的。谢谢!

解决方案

要向类的实例添加属性,您可以使用 .__ dict __
$ b

 b $ b self .__ dict __ [x] = val 

输出: / p>

 >>> 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'


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. Thanks!

解决方案

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

output:

>>> 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'

这篇关于Python - 动态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆