我对您的代码进行了一些调整,并使用基本继承来实现您的目标。
希望这就是你要找的!您应该在 LandArea 类中添加任意数量的位置,并在子类 Start_PubG 中引用它们。
class LandArea:
def bootcamp(self):
print ('You are landed in Bootcamp!')
def docks(self):
print('You are landed in Docks!')
class Start_PubG(LandArea):
def choose_land(self):
print('You are in the plane. Choose where to land!')
land_area = input('->')
if land_area.lower() == 'bootcamp':
super().bootcamp()
elif land_area.lower() == 'docks':
super().docks()
else:
print('Landed with bots')
obj = Start_PubG()
obj.choose_land()
***** 在您的评论后添加:******
嘿,您的场景应使用与上述相同的方法来实现,但您坚持使用 2 个不同的类。下面是相同的代码,
class Bootcamp:
def bootcamp(self):
print ('You are landed in Bootcamp!')
class Docks:
def docks(self):
print('You are landed in Docks!')
class Start_PubG(Bootcamp, Docks):
def choose_land(self):
print('You are in the plane. Choose where to land!')
land_area = input('->')
if land_area.lower() == 'bootcamp':
super().bootcamp()
elif land_area.lower() == 'docks':
super().docks()
else:
print('Landed with bots')
obj = Start_PubG()
obj.choose_land()
我也猜想,您想将用户输入转换为 Python 对象引用。如果是这样,您应该使用 eval() 函数来实现您的目标。以下是相同的方法。但是请确保用户提供的输入区分大小写并且与类名保持一致,因为字符串直接转换为 python 对象并被调用,因此当调用不存在的 python 对象时,此代码将引发错误。[与之前的方法不同,这种方法不区分大小写是无法处理的]
class Bootcamp:
def bootcamp(self):
print ('You are landed in Bootcamp!')
class Docks:
def docks(self):
print('You are landed in Docks!')
class Start_PubG(Bootcamp, Docks):
def choose_land(self):
print('You are in the plane. Choose where to land!')
land_area = input('->')
if land_area == 'Bootcamp':
obj_ref = eval(land_area)
obj_ref().bootcamp()
elif land_area == 'Docks':
obj_ref = eval(land_area)
obj_ref().docks()
else:
print('Landed with bots')
obj = Start_PubG()
obj.choose_land()