Python 复合函数参数

Python 复合函数参数,python,inheritance,Python,Inheritance,这是一个通过艰苦学习Python来实现*合成的示例。 此处的示例:——参见示例44.e(标题“合成”下) 当我使用呼叫时: self.other.implicit() Child()类是利用其他()类中函数定义的函数参数,还是利用Child()类中函数定义的参数? class Other(object): def override(self): print "OTHER override()" def implicit(self): prin

这是一个通过艰苦学习Python来实现*合成的示例。 此处的示例:——参见示例44.e(标题“合成”下)

当我使用呼叫时:

self.other.implicit()
Child()类是利用其他()类中函数定义的函数参数,还是利用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()类是从其他()类中的函数定义继承函数参数,还是利用Child()类中的函数定义的参数

它们都有相同的参数-一个位置参数(用于
self
)。因此,在这方面,函数之间没有区别

Child()类是否从其他()类中的函数定义继承函数参数

子项
不继承自
其他
;它继承自
对象
,因此不会有任何类型的继承

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这样的规则来覆盖 简单地说,它将匹配它调用的当前对象方法的参数w.r.t 若在当前对象中找不到这样的方法,它将查找父对象

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

在您的示例中,implicit In Other和implicit In Child是两个不同对象上的两个不同函数,

您向我们展示的代码是组合的示例,而不是继承的示例。Python没有函数原型,因此函数被名称覆盖。@jgomo3我很抱歉最初误述了我的问题,我更新了它以反映我最初的好奇心,希望措辞更好。我主要是想弄清楚在这种情况下函数参数是如何处理的。是否有一个层次结构的论点?参数必须相同才能引用另一个类中的函数吗?在它们不同的情况下,调用
self.other.implicit(),是否存在论点优先级的层次结构,或者论点必须匹配?@black_bird正如我的答案所解释的那样,没有继承权。我不相信你理解我的问题,或者我不完全理解你的答案。我想问的是
implicit()
的两个定义中如何处理函数参数。无论它是否被调用,我只是想知道在这种情况下,为了正确调用函数,必须如何设置参数,而不仅仅是调用
self
参数。@blackbird随便你怎么说。唯一的规则是第一个参数获取self对象。除此之外,你想做什么就做什么。这些类之间没有任何关系,除了一个调用另一个的方法所创建的内容。