根據用戶輸入更改屬性

[英]Changing attributes based on user input


Okay, I have a class which has 10 objects, these have the attributes self.planet, self.distance, self.distsquared, self.radius, self.diamater where distance/distsquared/radius/diamater are all integers. And I would like to make a function where the user searches for a planet name, and then changes one of the attributes.

好吧,我有一個有10個對象的類,它們具有self.planet,self.distance,self.distsquared,self.radius,self.diamater屬性,其中distance / distsquared / radius / diamater都是整數。我想創建一個用戶搜索行星名稱的功能,然后更改其中一個屬性。

For example, the user should input the name "Jupiter", which would then find the object, and the next row of the function would ask the user to add a certain sum to the attribute self.distance.

例如,用戶應輸入名稱“Jupiter”,然后找到該對象,該函數的下一行將要求用戶向屬性self.distance添加一定的總和。

Currently the first class is set up as following:

目前第一堂課的設置如下:

class Planets(): 
       def __init__(self, planetName, dist, radius, diameter): 
               self.planetName= planetName 
               self.dist= dist 
               self.radius= radius 
               self.diameter= diameter

This is then retrieved through a planetObjects=[Planets(*p) for p in planetList] This is the object-list I would like to turn into a dictionary so the user can search for planetName, and alter the distance

然后通過planetObjects = [行星(* p)為行星列表中的p檢索]這是我希望變成字典的對象列表,以便用戶可以搜索planetName,並改變距離

Some users suggested I use a dictionary for this, but I have no idea how to go about doing that. Currently my class turns a list of lists into a list of objects, these objects have these attributes that the user is supposed to be able to change by searching for the Planet name, and then changing one of its attributes.

一些用戶建議我使用字典,但我不知道如何去做。目前我的類將列表列表轉換為對象列表,這些對象具有用戶應該能夠通過搜索Planet名稱來更改的這些屬性,然后更改其中一個屬性。

The class is currently just a simple class which has a constructor and a __str__ function

該類目前只是一個具有構造函數和__str__函數的簡單類

Meaning, function starts, asks the user something like "Which planet would you like to alter?", the user inputs "Jupiter" and the program asks, "How has the distance to Jupiter changed?" where the user adds for example 450 or so.

意思是,功能開始,向用戶詢問“你想改變哪個星球?”,用戶輸入“Jupiter”並且程序詢問“木星的距離是如何變化的?”用戶添加的位置例如450左右。

The current code I have is a function which opens an infile and turns it into a list of lists. This list is then turned into objects. I turned it into objects to easily be able to sort it and add new values based on previous values. But at this point the user also has to be able to alter values by searching for a planet name and then changing one of the attributes - this is where I am lost and need help!

我當前的代碼是一個打開infile並將其轉換為列表列表的函數。然后將該列表轉換為對象。我將其轉換為對象,以便能夠輕松地對其進行排序並根據以前的值添加新值。但此時用戶還必須能夠通過搜索行星名稱然后更改其中一個屬性來更改值 - 這就是我迷失並需要幫助的地方!

Is there any way to do this? Thanks in advance!

有沒有辦法做到這一點?提前致謝!

2 个解决方案

#1


1  

In psuedocode:

class Planet(object):
    # Define your planet class here
    # any attributes that you do NOT need the user to be able to edit should start with _

Planets = [Planet('Mercury'.....
#or better
PlanetDict = {'Mercury':Planet(....

which = PromptUserForPlanet()

p = PlanetDict.get(which) # or find and return it if you didn't use a dictionary

for att in dir(p):
   if not att.startswith('_'):
      input = raw_input('%s: (%s)' % (attr, repr(getattr(p,attr)))
      if len(input) > 0:
         setattr(p,att,input) # You may wish to do some type conversion first

Since p is a reference to the dictionary entry you will change the main object.

由於p是對字典條目的引用,因此您將更改主對象。

#2


1  

Given your class Planets, this may be solved like this. I'm assuming that planetList is structured like in this code. If it is not, you may have to alter the code a bit.

鑒於你的類行星,這可能會像這樣解決。我假設planetList的結構與此代碼類似。如果不是,您可能需要稍微更改代碼。

def increment_dist(planets):
    name = raw_input('Please enter planet name')
    try:
        planets[name].dist += int(raw_input('Increment distance by (integer)'))
    except KeyError:
        print('No planet called {}'.format(name))
    except ValueError:
        print('That is not an integer')

planetList = [('Tellus', 1, 2, 4), ('Mars', 1, 3, 9)]
planet_dict = {name: Planets(name, dist, radius, diameter) for 
               name, dist, radius, diameter in planetList}

increment_dist(planet_dict)

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/11/24/724ff8a8d687d7ec4593c3d92e53336e.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com