Class with in class in python
我有一个classex.py文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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' |
我想,所以我想
例如:
1 2 3 | import classex print Class1.method1() print Class2.method2() |
我的期望是
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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' |
1 2 3 4 | >>> import classex >>> c = classex.Class1() # instance of Class1 >>> c.method1() stack1 |
号
实际上,您并没有导入类本身,而是只导入模块。
1 | import classex |
要访问类,您必须执行以下操作:
1 2 3 4 5 6 | >>> myclass = classex.Class1() >>> myclass2 = classex.Class2() >>> myclass.method1() stack1 >>> mycalss2.Class2.method2() over2 |
。
或者直接导入类:
1 2 3 4 5 6 7 | >>> from classex import Class1, Class2 >>> myclass = Class1() >>> myclass2 = Class2() >>> myclass.method1() stack1 >>> myclass2.method2() over2 |
或者你可以这样做
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | 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' |
。
然后
1 2 3 | import classex classex.Class1.method2() |
。
等。
但是你所做的并不能真正让我觉得你很好地理解OOP原则,或者你是从另一种OOP语言混合而来的,这种语言有一些一流的方法,你希望得到同样的结果。OO的Python实现略有不同于Java或C语言等,所以请务必阅读Python中如何定义方法的一点。