Skip to main content
 首页 » 编程设计

python之动态变量创建

2025年05月04日19xxx_UU

<分区>

我的问题是如何“即时”创建变量。我正在尝试生成一个具有一组随机属性的对象。

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) 

我很肯定我想这样做不是一个好方法,所以如果有人理解我在寻找什么并且可以提供更好的方法(一个有效的方法,对于初学者来说)我将不胜感激.