[英]Function Arguments with Composition
這是“艱苦學習Python”中*合成的示例。 在此處找到示例: 示例44-請參見示例44.e(在標題“ Composition”下)
使用通話時:
self.other.implicit()
Child()類是否利用了Other()類中的函數定義中的函數參數,還是利用了Child()類中的函數定義中的參數?
class Other(object):
def override(self):
print "OTHER override()"
def implicit(self):
print "OTHER implicit()"
def altered(self):
print "OTHER altered()"
class Child(object):
def __init__(self):
self.other = Other()
def implicit(self):
self.other.implicit()
def override(self):
print "CHILD override()"
def altered(self):
print "CHILD, BEFORE OTHER altered()"
self.other.altered()
print "CHILD, AFTER OTHER altered()"
son = Child()
son.implicit()
son.override()
son.altered()
Child()類是從Other()類中的函數定義中繼承函數自變量,還是利用Child()類中的函數定義中的變量?
它們都有相同的參數-一個位置參數(用於self
)。 因此,這方面的功能之間沒有區別。
Child()類是否從Other()類中的函數定義繼承函數參數
Child
不繼承Other
; 它繼承自object
,因此不會有任何形式的繼承。
class Other(object):
def __init__(self):
pass
def implicit(self, arg1, arg2):
print arg1
print arg2
class Child(Other):
def __init__(self):
pass
def implicit(self, arg1):
print arg1
Other().implicit(1, 2)
Child().implicit(3)
Output:
1
2
3
如果您考慮上述情況,則python中的參數無關緊要的Python是動態語言,因此您沒有像Java這樣的規則來覆蓋Simply如果它無法在當前中找到這樣的方法,它將與正在調用的當前對象方法的參數匹配對象,它將尋找父對象
class Other(object):
def __init__(self):
pass
def implicit(self, arg1, arg2):
print arg1
print arg2
class Child(Other):
def __init__(self):
pass
Child().implicit(3)
# will raise -> TypeError: implicit() takes exactly 3 arguments (2 given)
# as child does not have implicit method, we will look for method in parent(Other)
# which accepts 3 args (including self)
Child().implicit(1, 2) # this will work
output:
1
2
在您的示例中,其他隱式和子隱式是兩個不同對象上的兩個不同函數,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.