3 ms·
> The problem with an implicit "self", aside from it violating the Python Zen, is that it makes a number of cases nastily ambiguous. For example, consider the f
by anamax 17y ago
> The problem with an implicit "self", aside from it violating the Python Zen, is that it makes a number of cases nastily ambiguous. For example, consider the following method:
However, the syntax for the explicit self is somewhat awkward. Instead of:
def f(self, a, b): ...
it could have been
def self.f(a, b): ...
[This isn't original to me - Guido has mentioned it when he gets tired of hearing about explicit self.]
With the second, the structure of the argument list in the definition looks like the structure of the argument list in the call and the "self" is where the instance comes from relative to the method name.
- jmillikin 17y agoPlacing 'self' in the parameter list allows external procedures to be monkey-patched into a class, without needing to wrap it up in a 'partial'. For example: def foo(self, x): self.bar(x, 42) class MyClass: def bar(self, x, y): print ("%s %s" % (x, y)) MyClass.foo = foo While this is ugly, there are times when augmenting (or replacing) a class's existing methods is useful.
- sonoffett 17y agoI have found it very useful when writing unit tests for a particular method. I don't have to instantiate the class for which the method is a member of; instead I can easily pass a mock object as self that only contains the properties the method is supposed to test. Furthermore the claim that python doesn't support objects cleanly or easily is unfounded: 1) everything is an object in python (http://diveintopython.org/getting_to_know_python/everything_is_an_object.html http://diveintopython.org/getting_to_know_python/everything_...), including classes. 2) properties of an object are accessed in just the same way as in Java (obj.property), I don't understand where the confusion lies.
- anamax 17y agothe def self.foo(x): syntax does not interfere with such monkey patching because it gets turned into foo = {fn using (self, x)}.