动态变量创建

编程入门 行业动态 更新时间:2024-10-22 23:07:42
本文介绍了动态变量创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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'

更多推荐

动态变量创建

本文发布于:2023-11-28 07:25:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641463.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!