3 ms·
> It's not that it's confusing, rather it's unnecesarrely cumbersome because it's explicit and because you have to put it as an argument. I don't feel the same
by scriptkiddy 10y ago
> It's not that it's confusing, rather it's unnecesarrely cumbersome because it's explicit and because you have to put it as an argument.
I don't feel the same way. To each their own I guess.
Regarding your example, I don't see anything wrong with the second version. Anyone who reads the code will easily be able to tell what it does and where the variables come from. In your third example, how is anyone supposed to know whether or not `x`, `y`, and `z` are class variables or global variables? Kind of defeats the purpose of namespacing, I think.
> What I find worse than that is that you have to specify self in the parameter list.
This is really one of Python's implementation details. Methods can be bound or unbound. Without going into to much detail, just know that a bound method can be used as a regular function. Here is some code to illustrate what I mean:
>>> class A():
... def a(self):
... print('hello')
...
>>> A
<class '__main__.A'>
>>> A.a
<function A.a at 0x7fc4009381e0>
>>> A.a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a() missing 1 required positional argument: 'self'
>>> A().a()
hello
>>> b = A()
>>> A.a(b)
hello
>>> class B():
... pass
...
>>> b = B()
>>> A.a(b)
hello
>>> class B():
... def a(self):
... print('goodbye')
...
>>> b = B()
>>> A.a(b)
hello
>>> c = A()
>>> B.a(c)
goodbye
Self does not have to be the same class it's called on. It can be any class. However, if you try to access a class attribute that doesn't exist, you get an attribute error.
>>> class C():
... x = 10
... def a(self):
... print(self.x)
...
>>> C.a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a() missing 1 required positional argument: 'self'
>>> C().a()
10
>>> a = A()
>>> a.a()
hello
>>> C.a(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in a
AttributeError: 'A' object has no attribute 'x'
Since bound methods need to behave like regular functions, it is improper to not pass the object instance to the function.