为什么需要在Python方法中显式包含" self"参数?
时间:2020-03-05 18:54:52 来源:igfitidea点击:
在Python中的类上定义方法时,它看起来像这样:
class MyClass(object): def __init__(self, x, y): self.x = x self.y = y
但是在某些其他语言中,例如C#,我们可以使用" this"关键字来引用该方法所绑定的对象,而无需在方法原型中将其声明为参数。
这是Python中的故意语言设计决定,还是有一些实现细节需要传递"自我"作为参数?
解决方案
回答
这是为了最小化方法和函数之间的差异。它使我们可以轻松地在元类中生成方法,或者在运行时将方法添加到预先存在的类中。
例如
>>> class C(object): ... def foo(self): ... print "Hi!" ... >>> >>> def bar(self): ... print "Bork bork bork!" ... >>> >>> c = C() >>> C.bar = bar >>> c.bar() Bork bork bork! >>> c.foo() Hi! >>>
据我所知,这也使python运行时的实现更加容易。
回答
我喜欢引用Peters的Python Zen。 "显式比隐式好。"
在Java和C ++中,可以推导出" this。",除非我们具有无法推论的变量名。因此,我们有时需要它,有时则不需要。
Python选择使这种事情变得明确,而不是基于规则。
另外,由于没有暗示或者假设,因此公开了部分实现。 self .__ class__,
self .__ dict__`和其他"内部"结构以明显的方式可用。
回答
还有一个非常简单的答案:根据python的禅宗,"显式比隐式更好"。
回答
Python不会强迫我们使用"自我"。我们可以根据需要命名。我们只需要记住,方法定义标头中的第一个参数是对该对象的引用。
回答
我建议人们应该阅读Guido van Rossum关于此主题的博客,为什么显性自我必须保留。
When a method definition is decorated, we don't know whether to automatically give it a 'self' parameter or not: the decorator could turn the function into a static method (which has no 'self'), or a class method (which has a funny kind of self that refers to a class instead of an instance), or it could do something completely different (it's trivial to write a decorator that implements '@classmethod' or '@staticmethod' in pure Python). There's no way without knowing what the decorator does whether to endow the method being defined with an implicit 'self' argument or not. I reject hacks like special-casing '@classmethod' and '@staticmethod'.