【发布时间】: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