0

我有一个 classex.py 文件:

class Class1:
    def method1():
        print 'stack1'
    def method2():
        print 'over1'
    def method3():
        print 'flow1'

class Class2:
    def method1():
        print 'stack2'
    def method2():
        print 'over2'
    def method3():
        print 'flow2'

class Class3:
    def method1():
        print 'stack3'
    def method2():
        print 'over3'
    def method3():
        print 'flow3'

我想要访问classex文件类,所以我将导入该文件如何在各种类中访问。

例如:

import classex
print Class1.method1()
print Class2.method2()

我的期望输出是stack1over2

4

3 回答 3

5
class Class1:
    def method1(self): # instance  is passed implicity as first arg
        print 'stack1'
    def method2(self):
        print 'over1'
    def method3(self):
        print 'flow1'

class Class2:
    def method1(self):
        print 'stack2'
    def method2(self):
        print 'over2'
    def method3(self):
        print 'flow2'

class Class3:
    def method1(self):
        print 'stack3'
    def method2(self):
        print 'over3'
    def method3(self):
        print 'flow3'

>>> import classex
>>> c = classex.Class1() # instance of Class1
>>> c.method1()
stack1
于 2013-04-20T10:07:32.820 回答
2

您实际上并没有导入类本身,而只是导入了模块。

import classex

为了访问您必须执行的课程:

>>> myclass = classex.Class1()
>>> myclass2 = classex.Class2()
>>> myclass.method1()
stack1
>>> mycalss2.Class2.method2()
over2

或者直接导入类:

>>> from classex import Class1, Class2
>>> myclass = Class1()
>>> myclass2 = Class2()
>>> myclass.method1()
stack1
>>> myclass2.method2()
over2
于 2013-04-20T10:07:44.740 回答
0

或者你可以这样做

class Class1:
    @classmethod
    def method1(clss):
        print 'stack1'
    @classmethod
    def method2(clss):
        print 'over1'
    @classmethod
    def method3(clss):
        print 'flow1'

class Class2:
    @classmethod
    def method1(clss):
        print 'stack2'
    @classmethod
    def method2(clss):
        print 'over2'
    @classmethod
    def method3(clss):
        print 'flow2'

class Class3:
    @classmethod
    def method1(clss):
        print 'stack3'
    @classmethod
    def method2(clss):
        print 'over3'
    @classmethod
    def method3(clss):
        print 'flow3'

接着

import classex

classex.Class1.method2()

等等

但是你所做的并没有真正让我觉得你很好地理解了 OOP 原则,或者你来自另一种 OOP 语言,它有一些类方法之王,你希望得到相同的结果. OO 的 Python 实现与 Java 或 C# 等略有不同,因此请务必阅读一点关于如何在 Python 中定义方法的内容。

于 2013-04-20T10:21:59.577 回答