在Python中定义类的方法时,它看起来像这样:
class MyClass(object):
def __init__(self, x, y):
self.x = x
self.y = y
但是在其他一些语言中,比如c#,你有一个对象的引用,这个对象是用"this"关键字绑定的,而不是在方法原型中作为参数声明的。
这是Python中有意的语言设计决策,还是有一些实现细节需要传递“self”作为参数?
在Python中定义类的方法时,它看起来像这样:
class MyClass(object):
def __init__(self, x, y):
self.x = x
self.y = y
但是在其他一些语言中,比如c#,你有一个对象的引用,这个对象是用"this"关键字绑定的,而不是在方法原型中作为参数声明的。
这是Python中有意的语言设计决策,还是有一些实现细节需要传递“self”作为参数?
当前回答
这是为了最小化方法和函数之间的差异。它允许您轻松地在元类中生成方法,或在运行时向已存在的类添加方法。
e.g.
>>> class C:
... 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运行时的实现更容易。
其他回答
我建议大家应该读读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'.
我认为除了“Python之禅”之外,真正的原因是函数是Python中的第一类公民。
这本质上使它们成为对象。最基本的问题是如果你的函数也是对象那么在面向对象的范例中当消息本身是对象时你将如何向对象发送消息?
看起来像一个先有鸡还是先有蛋的问题,为了减少这种矛盾,唯一可能的方法是将执行上下文传递给方法或检测它。但是由于python可以有嵌套函数,因此不可能这样做,因为内部函数的执行上下文会发生变化。
这意味着唯一可能的解决方案是显式传递'self'(执行上下文)。
所以我认为这是一个执行问题,禅宗来得晚了很多。
Python不会强制你使用"self"。你可以给它起任何你想要的名字。你只需要记住方法定义头中的第一个参数是对对象的引用。
我认为这和PEP 227有关
Names in class scope are not accessible. Names are resolved in the innermost enclosing function scope. If a class definition occurs in a chain of nested scopes, the resolution process skips class definitions. This rule prevents odd interactions between class attributes and local variable access. If a name binding operation occurs in a class definition, it creates an attribute on the resulting class object. To access this variable in a method, or in a function nested within a method, an attribute reference must be used, either via self or via the class name.
还有另一个非常简单的答案:根据python的禅宗,“显式比隐式好”。