[英]Python using methods from other classes
如果我有兩個類,並且其中一個類具有我想在其他類中使用的函數,那么我使用什么以便我不必重寫我的函數?
有兩種選擇:
例:
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")
您創建一個類,兩個類都從該類繼承。
有多個繼承,所以如果他們已經有父,那就不是問題了。
class master ():
def stuff (self):
pass
class first (master):
pass
class second (master):
pass
ichi=first()
ni=second()
ichi.stuff()
ni.stuff()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.