【问题标题】:Is there a way to call an instance of a class with a string variable? [duplicate]有没有办法用字符串变量调用类的实例? [复制]
【发布时间】:2022-01-09 08:20:10
【问题描述】:

我是编程方面的菜鸟,目前正在为基于科幻的 TTRPG 构建世界。我正在尝试自动生成我的世界中的各种事物,例如行星等。其中之一是船舶生成。我为我的船创建了一个类:

class starShip:
    def __init__(self, cost, speed, armour):
        self.cost = cost
        self.speed = speed
        self.armour = armour

还有几个例子:

shuttle = starShip(200000,3,0)
fighter = starShip(500000,5,5)

我正在使用 pandas 和一个 csv 文件来随机化生成的船只。例如:

def shipGenerator(rowNum):
    for col in dfShips.columns:
       if col == "Ship Type": #need to find relevant column header in the original data frame
       result = randint(1,20) #give random number
       shipType = dfShips.loc[result,"Ship Type"] #get the value from relevant cell in original data frame
       dfGeneratedShips.at[rowNum,col] = shipType #generate the ship type in a new dataframe

现在我可以为每种类型的船做很多 if/elif - if 穿梭,然后将Shuttle.cost(starShip 类的实例)放入相关的成本单元等等等。但是有 12 种不同类型的船,这是很多 if/elif,我正在努力做到这一点,即使这是一个有趣的项目,而且我是一个完全的菜鸟。所以我的问题是,有没有办法使用字符串变量来调用实例?例如,变量 shipType 现在包含“shuttle”或“fighter”。有没有办法使用该变量调用 starShip 类的实例?喜欢:

dfGeneratedShips.loc[rowNum,"Cost"] = shipType.cost #place the cost of the relevant ship type under the appropriate column in new dataframe
dfGeneratedShips.loc[rowNum,"Speed"] = shipType.speed

但是shipType在循环的每次迭代中都指的是“航天飞机”或“战斗机”或“航母”,因此结果会发生适当的变化。

我希望这已经足够清楚了,感谢您的帮助!

【问题讨论】:

  • 你应该有ships['shuttle']ships['fighter']
  • 术语说明:您的意思不是“调用”一词,而是“参考”。例如“我可以使用字符串引用对象吗”。调用的意思是“调用函数”(或任何“可调用的”)。 myfunction()
  • 感谢您让我知道 - 如上所述,非常新手。这也一定是谷歌搜索这个问题不起作用的原因——我使用了错误的术语! =/

标签: python python-3.x class


【解决方案1】:

字典可以做到..

ships = {"shuttle":starShip(200000,3,0),"fighter":starShip(500000,5,5)}  

你可以的

ships["shuttle"].cost
ships["shuttle"].speed

【讨论】:

  • 顺便说一句,这是一个常见问题解答。 (当我准备找到一个副本来关闭它时,你就回答了)。
  • 这是很棒的东西,非常感谢!
  • @CharlesDuffy 我认为我的回答比“如何创建变量变量”更有用,后者需要 OP 建立实例也是变量的连接而不是明确的。
  • @JeffUK,当然——我有时会写一个社区 wiki 答案(将 CW 标记为不会因回答已知重复而获得代表点,并明确表示欢迎其他人进行编辑)显示如何在我自己关闭某些东西作为副本时,在 OP 的特定场景中应用一种技术。但这并不意味着它不是重复的,链接副本中接受的答案确实非常显示了这种技术。
  • @CharlesDuffy 这听起来像是通过回答他们的问题来帮助 OP.. 只是有很多额外的步骤!
猜你喜欢
  • 1970-01-01
  • 2021-10-14
  • 1970-01-01
  • 2019-12-21
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
  • 1970-01-01
  • 2012-05-12
相关资源
最近更新 更多