Instead of doing the following:
def MyFunc(self, a, b, c)
self.a = a
self.b = b
self.c = c
I want to do the following:
def MyFunc(self, self.a, self.b, self.c)
Why does this not work?
This doesn't work because it simply invalid syntax. Python will not allow for you to use self.
because your syntax is not valid. Lets take look at the EBNF for function arguments in Python:
parameters: '(' [typedargslist] ')'
typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [','
['*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' >tfpdef]]
| '*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' >tfpdef)
tfpdef: NAME [':' test]
You may or may not be able to tell from the above snippet of EBNF, but Python does not allow the .
operator in parameters. That is why your second method doesn't work.
Lets assume though, that your second example was valid Python syntax. Would it work? The short answer is still no. This is simple because of how Python parses function/method parameters. Lets look at this example:
>>> class Foo:
def __init__(self):
pass
def bar(self, x=self):
pass
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
class Foo:
File "<pyshell#13>", line 4, in Foo
def bar(self, x=self):
NameError: name 'self' is not defined
>>>
What happened? Why did Python raise a NameError
when self
is clearly defined.
While Python is in the middle of parsing bar
is sees the parameter self
. But while Python has "seen" the self
parameter, it had not defined it as a name. So when Python tries to parse the second parameter, it becomes confused, and raises a NameError
. This behavior is not just exclusive to
methods however. Functions have the same problems as well:
>>> def foo(a, b=a+1):
return a, b
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
def foo(a, b=a+1):
NameError: name 'a' is not defined
To sum it up; The real reason that your second examples doesn't work is because it's invalid Python syntax. But even if it did somehow work, Python would still raise an error due to the way it parses parameters.