首页 > 解决方案 > 习惯函数 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()

因此,它似乎没有定义位置类型。请记住,我正在尝试使用尽可能少的代码行。

标签: pythonpython-3.x

解决方案


当您引用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会使您引用的变量不那么模棱两可。


推荐阅读