Python在函数内的类中调用导入模块中的函数

时间:2017-04-27 16:22:05

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

我有这个问题。我目前有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()

1 个答案:

答案 0 :(得分:0)

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()