如果我有两个类,而其中一个有一个要在其他类中使用的函数,那么该使用什么,这样就不必重写我的函数了?
有两种选择:
例:
class A(object): def a1(self): """ This is an instance method. """ print "Hello from an instance of A" @classmethod def a2(cls): """ This a classmethod. """ print "Hello from class A" class B(object): def b1(self): print A().a1() # => prints 'Hello from an instance of A' print A.a2() # => 'Hello from class A'
或使用继承(如果适用):
class A(object): def a1(self): print "Hello from Superclass" class B(A): pass B().a1() # => prints 'Hello from Superclass'