【问题标题】:Python Calling a function within a class, within a function, from an imported modulePython 从导入的模块中调用类内、函数内的函数
【发布时间】:2017-04-27 16:22:05
【问题描述】:

我有这个问题。我目前有 2 个文件。我正在尝试打印“Hello World Trudy”字样。我无法解决这个问题。它一直告诉我我有一个属性错误。我该怎么做才能解决它?

Traceback (most recent call last):
  File "C:\Users\Trudy\Desktop\PythonLearning\test2.py", line 7, in <module>
    f.sayHello()
AttributeError: 'NoneType' object has no attribute 'C'

test1.py

def main():
    class C:
        def function6(self):
            print ("Hello")
        def function7(self):
            print ("Trudy")
    def sayHello():
        C().function6()
    def sayWorld():
        C().function7()


if __name__ == "__main__":
    main()

test2.py

import test1
def function2():
    print ("World")

test1.main().C.function6()
function2()

【问题讨论】:

  • main 函数是怎么回事?它为什么存在?此外,您只使用一个 Python 版本。不要标记多个。
  • main() 是一个不返回任何内容的函数(因此它的返回类型是NoneType)。您不能从块外部访问功能块内定义的类。
  • 为什么要在函数内部声明一个类?你为什么要做C().function6() 而不是在某处存储C 的实例?你到底想做什么?你想用这段代码解决什么问题?
  • 一些推荐阅读docs.python.org/2/tutorial/classes.html,正如文档建议的那样,请先阅读范围和命名空间。
  • 大家好,对不起。我对 Python 真的很陌生!将阅读文档并试图弄清楚。非常感谢大家!

标签: python algorithm python-2.7 python-3.x python-import


【解决方案1】:

你不需要 test1 文件中的 main 函数。只要有C类在那里。

test1.py

class C:
    def function6(self):
        print ("Hello")
    def function7(self):
        print ("Trudy")
 def sayHello():
    C().function6()
 def sayWorld():
    C().function7()

test2.py

import test1
def function2():
    print ("World")

test1.C().function6()
function2()

【讨论】:

    猜你喜欢
    • 2013-07-31
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 2015-03-05
    • 1970-01-01
    • 2016-01-03
    • 2016-03-16
    相关资源
    最近更新 更多