Python-动态变量

2024-04-18 12:47:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题是如何“动态”创建变量。我试图生成一个具有随机属性集的对象。

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)

我很肯定我想怎么做不是一个好办法,所以如果有人明白我在寻找什么,并能提供一个更好的方法(一个工作,首先)我会非常感激。谢谢!


Tags: inselfforvarlocalrandomattributesperson
3条回答

要向类的实例添加属性,可以使用.__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'

使用vars。例如:

>>> import math
>>> class foo: pass
>>> vars(foo)
{'__module__': '__main__', '__doc__': None}
>>> vars(foo)['fn']=math.sin
>>> foo.fn(2)
0.9092974268256817
>>> vars(foo)
{'__module__': '__main__', '__doc__': None, 'fn': <built-in function sin>}

如您所知,方法只是多了一个参数的函数。

好吧,我不知道你想在这里实现什么,但这里可能有一些事情。。。。

class Person(object):
    def __init__(self):
        self.attributes = [] 

这定义了一个类对象,您可以从中创建包含attributes的对象,我们可以从__init__或构造函数(在某些其他语言中调用)中看到。

但是你有

Person.attributes.append(local_var)

这里的Person是一个类对象,它实际上没有define since的属性,而define since的属性只用于从这个类创建的对象。。。

您可以创建一个新的人员并为其添加适当的属性。

>>> me = Person()
>>> me.attributes.append('humble')

其次,我们真的不应该直接访问属性,因为任何东西都可以附加到列表中,包括重复的属性。

所以为什么不简单地添加一个添加属性的函数呢。

class Person(object):
    def __init__(self):
        self._attributes = [] # note any variable starting with _ is meant to be private 
    def add_attribute(attribute):
        if attribute not in self._attributes:
            self._attributes.append(attribute)

如果性能是一个问题,我们可以使用set()而不是[],因为它不允许重复条目和快速检查任何查找,缺点是值必须是可哈希的ie字符串、int或其他简单数据类型。。。

相关问题 更多 >