我有一个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()
我的预期输出为stack1
和over2
答案 0 :(得分: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
答案 1 :(得分:2)
您实际上并没有导入Classes本身,而只是导入模块。
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
答案 2 :(得分: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中定义方法的内容。