【问题标题】:Customary Functions Python 3.7习惯函数 Python 3.7
【发布时间】: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


【解决方案1】:

当您引用location_type 时,您必须牢记您的scope。当您在类内调用函数时,该函数无法访问类的范围,因为它是在类外部定义的。

另外,我建议在__init__ 之后运行函数location_screen,以确保您首先拥有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 可以使您引用的变量不那么模糊。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-15
    • 2017-09-11
    • 2019-06-16
    • 2019-05-18
    • 2010-11-14
    • 2017-06-06
    • 2015-05-24
    • 1970-01-01
    相关资源
    最近更新 更多