python - 习惯函数 Python 3.7
问题描述
我正在为家庭作业制作一个游戏,它会在学校各处巡回演出。我有比较好的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()
因此,它似乎没有定义位置类型。请记住,我正在尝试使用尽可能少的代码行。
解决方案
当您引用location_type
时,您必须牢记您的范围。当您在类内部调用函数时,该函数无法访问类的范围,因为它是在类外部定义的。
另外,我建议location_screen
在 in 之后运行该功能,__init__
以确保您location_type
首先拥有。此外,self
在您的范围内使用更具体。代码如下所示:
class Schoolgates():
def __init__(self):
# set the location type for this instance of the object
self.location_type = "This is a nifty location"
# call the method based on this instance of the object
self.location_screen()
def location_screen(self):
if self.location_type == 'What ever':
print ('''
This is location type what ever''')
elif self.location_type == 'This is a nifty location':
print ('''
This is location type what ever''')
当然,如果方法是在Schoolgates
类中定义的,您仍然可以像上面那样设置变量,但是使用self
会使您引用的变量不那么模棱两可。
推荐阅读
- javascript - 从打字稿文件中存在的html元素调用函数(Angular)
- javascript - Apollo 客户端 TypeError:value.subscribe 不是函数
- vuejs2 - 从远程主机到本地主机名的 Vue SocketIO 连接 (http://myhostname.local)
- python - 通过python在jira中获取所需时区的问题
- node.js - 什么是 ”“?
- javascript - GPU 和 FPS 瓶颈和延迟增加
- python - Gevent 车轮无法制造
- json - 如何将对象添加到 Firebase RTDB
- python - Groupby /合并/汇总数据框
- java - @OneToOne 注释中的外键问题