Python:在函数中使用在类内完成的导入 [英] Python: Use an import done inside of a class in a function

查看:22
本文介绍了Python:在函数中使用在类内完成的导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下如何使下面的示例工作?由于类中的几个函数将使用来自Platform的相同函数,我认为直接将其导入到类中会更好,但我不知道如何在函数中使用它(因为我经常收到有关它的错误)。

#!/usr/bin/python

class test:
   from platform import system
   is_linux(self):
      system = system()
      if system == "Linux": return True

更好的例子:

#!/usr/bin/python

# Add ANSI colour strings
class stdout:
    from sys import stdout
    def message(message, self):  stdout.write(message)

注意:这只是一个片断,有些部分遗漏了,但这是我的意思的一个示例。
我知道我可能只需移动system = system()并使用self.system,但也许有更好的方法?

推荐答案

嗯,事情没有那么简单。 实际上,IMPORT语句在很多方面看起来都像是对某物的直接定义。如果您写

class test:
    from platform import system

它看起来完全像

class test:
    def system():
        # ....

然后您会遇到以下问题:

  1. 您不能只使用system(),因为系统不在全局作用域中
  2. 您不能使用self.system(),因为在此表单中,python自动传递self作为第一个参数,但system()没有参数,您将获得TypeError: system() takes no arguments (1 given)
  3. 您不能使用test.system(),因为system()看起来像一个普通的方法,您将得到TypeError: unbound method system() must be called with test instance as first argument (got nothing instead)

解决这些问题有几种方法:

  1. import platform放在顶层,并在您想要的任何地方使用Platform.system(),这样就从Prev修复了问题#1。列表
  2. 使用staticmethod修饰器,修复来自Prev的问题#2和#3。列表。

喜欢

class test:
    from platform import system
    system = staticmethod(system)

然后您可以使用self.system()或est.system()

实际上,您应该只导入TopLevel中的所有内容,然后忘掉它。 只有在运行时需要特殊的东西时,才需要拆分导入声明。 如

import foo
import bar

def fun(param1, param2):
    # .....

if __name__ == '__main__':
    from sys import argv
    if len(argv) > 2:
        fun(argv[1], argv[2])
在本例中,移动from sys import argv是有效的,因为只有在运行脚本时才需要它。但当您将其用作导入的模块时,不需要进行此导入。 但这不是您的情况,因为在您的情况下,测试类总是需要system(),因此没有理由将此导入从TopLevel移出。就把它放在那里吧,没关系。

这篇关于Python:在函数中使用在类内完成的导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆