基于用户输入更改属性

2024-10-08 18:25:31 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我有一个类,有10个对象,它们有属性自我星球, 自我距离, 自平方分布, 自半径, 自身直径其中距离/距离平方/半径/直径都是整数。我想做一个函数,用户搜索一个行星名称,然后更改其中一个属性。你知道吗

例如,用户应该输入名称“Jupiter”,然后它将找到对象,函数的下一行将要求用户向属性添加一定的和自我距离. 你知道吗

目前第一节课设置如下:

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

然后通过planetObjects=[Planets(*p) for p in planetList]检索,这是我想变成字典的对象列表,这样用户就可以搜索planetName并改变距离

有些用户建议我用字典来做这个,但我不知道该怎么做。目前,我的类将列表列表转换为对象列表,这些对象具有这些属性,用户应该能够通过搜索行星名称,然后更改其中一个属性来更改这些属性。你知道吗

这个类目前只是一个简单的类,它有一个构造函数和一个__str__函数

也就是说,函数启动后,会询问用户“你想改变哪个星球?”,用户输入“Jupiter”,程序会问,“到Jupiter的距离是如何变化的?”其中用户添加例如450左右。你知道吗

我当前的代码是一个函数,它打开一个infile并将其转换为列表列表。然后将此列表转换为对象。我将其转换为对象,以便能够轻松地对其进行排序,并根据以前的值添加新值。但在这一点上,用户还必须能够通过搜索一个行星名称,然后更改其中一个属性来更改值-这就是我迷路的地方,需要帮助!你知道吗

有什么办法吗?提前谢谢!你知道吗


Tags: 对象函数用户self名称距离列表属性
2条回答

在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

因为p是对字典条目的引用,所以您将更改main对象。你知道吗

给你的类Planets,这个问题可以这样解决。我假设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)

相关问题 更多 >

    热门问题