2012-08-15 102 views
1

我的問題是如何在運行中創建變量。我試圖用隨機的一組屬性來生成一個對象。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) 

我敢肯定我怎樣,我想這樣做,這不是一個好辦法,所以如果有人明白我在尋找,並能夠提供更好的方法(一個工程,對於初學者)我將是最感激。謝謝!

+3

這是...非常爛。改用字典。 – 2012-08-15 04:19:23

+0

爲什麼你需要VAR是'全球'?構建具有所有期望屬性的Person實例有什麼問題? – 2012-08-15 04:20:40

+0

我認爲這個問題是你需要弄清楚如何避免這種情況。字典和列表做了很棒的工作。 – 2012-08-15 04:24:17

回答

1

添加屬性的類的實例可以使用.__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' 
+1

更簡單的就是使用'setattr()'。 – Duncan 2012-08-15 11:21:32

0

這是怎麼了,我可能構造對象與一組隨機屬性,給定你的定義:

import random 

possible_attributes= ['small', 'black', 'scary', 'smelly', 'happy'] 

class Person(object): 
    def __init__(self): 
     self.attributes = random.sample(possible_attributes, random.randint(0, len(possible_attributes))) 

這會從您的可能屬性列表中選擇一個隨機數的屬性。

>>> print Person().attributes 
['small', 'smelly'] 
>>> print Person().attributes 
['scary', 'smelly', 'happy'] 
0

通常,不要污染全局命名空間,您不希望添加到全局變量。字典提供了一個命名空間般的方式來訪問的一切,但如果你真的要使用全局變量()[X] =一些修改的項目,或者使用很討厭

exec "var_name=somehting" 
+1

我會高度暗示_against_使用'exec',除非你_really_ - 不,**真的** - 知道你爲什麼需要它。 – voithos 2012-08-15 04:22:44

+0

這就是爲什麼我說「討厭」的原因 – 2012-08-15 04:23:19

+1

事實:exec會減慢你的整個程序,因爲Python必須關閉一些本來可以做的優化。 – 2012-08-15 04:25:47

1

使用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>} 

正如你所知,方法只是帶有一個參數的函數。

1

儘管我不能確切地告訴你需要什麼,但我猜測你實際上並不需要全局變量,只有一個具有隨機/動態屬性集的Person對象。對於這一點,你要setattrrandom.sample()

crazy_person = Person() 
selected_attribute_names = random.sample(possible_attributes, 3) 
for attribute_name in selected_attribute_names: 
    setattr(crazy_person, attribute_name, True) 

# optional -- if you want to have a list of attributes, just copy that in: 
crazy_person.attributes = selected_attribute_names 
# vars(crazy_person).keys() will give you more or less the same thing though, for free 

# hasattr(crazy_person, 'small') will tell you if you picked 'small' 
# if we chose 'small', then from here on, crazy_person.small will be True as well 
1

嗯林不知道你是什麼綁在這裏實現,但可能有幾件事情在這裏下車....

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

這定義一個類對象,您可以從中創建包含attributes的對象,如我們從__init__或構造函數可以看到的那樣在其他語言中調用該對象。

,但你必須

Person.attributes.append(local_var) 

這裏Person是一個類的對象真的不具備的屬性是哪裏定義,因爲不只是從這個類創建的對象......

可以創建一個新人並向他們添加適當的屬性。

>>> 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()代替[],因爲它不允許重複條目和真快檢查任何查找的缺點是值必須散列能即字符串或關注整數或其他簡單的數據類型...

+0

對。這只是僞代碼。我想盡量簡短,但我不知道,謝謝你花時間通知我! :)我在其他帖子中一直不太簡短,所以我這次做了一個努力,並反過來投票發佈了一些看起來不太好的東西......我可能會避免從現在開始在這裏張貼。 (我爲隨機咆哮道歉,我現在脾氣暴躁) – jtsmith1287 2012-08-15 05:11:14