【发布时间】:2011-02-17 08:03:37
【问题描述】:
如果我有两个类,其中一个有一个我想在另一个类中使用的函数,我应该使用什么来避免重写我的函数?
【问题讨论】:
如果我有两个类,其中一个有一个我想在另一个类中使用的函数,我应该使用什么来避免重写我的函数?
【问题讨论】:
您创建一个类,两个类都从该类继承。
有多重继承,所以如果他们已经有一个父级,那不是问题。
class master ():
def stuff (self):
pass
class first (master):
pass
class second (master):
pass
ichi=first()
ni=second()
ichi.stuff()
ni.stuff()
【讨论】:
有两种选择:
例子:
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'
【讨论】:
有几种方法:
以下示例使用每个示例来共享一个打印成员的函数。
继承
class Common(object):
def __init__(self,x):
self.x = x
def sharedMethod(self):
print self.x
class Alpha(Common):
def __init__(self):
Common.__init__(self,"Alpha")
class Bravo(Common):
def __init__(self):
Common.__init__(self,"Bravo")
代表团
class Common(object):
def __init__(self,x):
self.x = x
def sharedMethod(self):
print self.x
class Alpha(object):
def __init__(self):
self.common = Common("Alpha")
def sharedMethod(self):
self.common.sharedMethod()
class Bravo(object):
def __init__(self):
self.common = Common("Bravo")
def sharedMethod(self):
self.common.sharedMethod()
超级偷偷摸摸的委派
该解决方案基于以下事实:Python 成员函数没有什么特别之处。只要第一个参数被解释为类的实例,你就可以使用任何函数或可调用对象。
def commonPrint(self):
print self.x
class Alpha(object):
def __init__(self):
self.x = "Alpha"
sharedMethod = commonPrint
class Bravo(object):
def __init__(self):
self.x = "Bravo"
sharedMethod = commonPrint
或者,实现委托的一种类似偷偷摸摸的方法是使用可调用对象:
class Printable(object):
def __init__(self,x):
self.x = x
def __call__(self):
print self.x
class Alpha(object):
def __init__(self):
self.sharedMethod = Printable("Alpha")
class Bravo(object):
def __init__(self):
self.sharedMethod = Printable("Bravo")
【讨论】:
Alpha().sharedMethod(),你会得到NameError: name 'x' is not defined