通过导入访问另一个类对象



我有一个程序名称"new.py":

class hello:
    def __init__(self, summary):
        self.summary = summary

    def hi(self):
        print self.summary
if __name__ == "__main__":
    h = hello(summary = "this is a hello program")
    h.hi()

当我想访问功能hi到另一个程序名称 another.py 时,我无法访问该功能..请帮助我并纠正我...another.py:

import new 
    class another:
        def __init__(self, value):
            self.value = value
        def show(self):
            print "value is %s" % self.value
            new.hi()
            print "done"
    if __name__ == "__main__":
        a = another(value = "this is a another value")
        a.show()

输出:

new.hi()
AttributeError: 'module' object has no attribute hi

问题是您没有初始化 hello 对象。因此,在调用 hi 函数之前,您需要在某个地方执行此操作:

        n  = new.hello('some string')

然后,您可以致电:

       n.hi()

实际问题是你这样做:

import new

然后:

new.hi()
hi() 不是在 new 中定义的,

它是在 new.hello 中定义的,这是你的类。您需要创建类 hello 的新实例并从那里调用 hi()。

相关内容

最新更新