gpt4 book ai didi

python - 动态变量创建

转载 作者:太空宇宙 更新时间:2023-11-04 08:17:21 25 4
gpt4 key购买 nike

<分区>

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

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)

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com