【发布时间】:2019-07-06 04:14:13
【问题描述】:
我正在为家庭作业制作一个游戏,它会在学校各处巡回演出。我有比较好的python编码技能。这个问题更像是一个操作方法而不是一个为什么的问题。
所以问题是你如何制作一个根据它所在的类而改变的函数。这是一个例子。
def location_screen():
if location_type == 'What ever':
print ('''
This is location type what ever''')
elif location_type == 'This is a nifty location':
print ('''
This is location type what ever''')
现在我希望结果在告诉函数其位置类型的类中。示例:
class Schoolgates():
location_type = "This is a nifty location"
location_screen()
所以,它似乎没有定义位置类型。请记住,我正在尝试使用尽可能少的代码行。
【问题讨论】:
-
为什么不把它需要的东西传递给函数呢?对隐式输入使用非局部变量不是很干净的编码。无论如何,您正在尝试做的是被 Python 的词法范围规则所阻挠。有一些变通方法,但最好重构代码。
-
我假设 location_screen 函数没有在类中定义?如果是这样,您可以直接将一个字符串传递给它
class Schoolgates: location_message = "print this" location_screen(location_message)然后在 location_screen 中直接打印参数而不是检查类型您也可以将函数定义为类的一部分,这样它就需要一个 self 参数def location_screen(self): print(self.location_message)它将允许您直接访问在类(或类的实例)中定义的属性 -
“[函数]在哪个类中”是什么意思?如果函数是相关类的成员,你可以使用
self.location_type? -
我的意思是,有几种不同类型的位置,例如(教室、走廊等)同样的事情。
标签: python python-3.x