IMHO, TR1 support and auto
are safe to use. In the case of auto
it was one of the first features to be included into the standard and is a relatively small change to the language. I would therefore have no problem using it.
I would be a bit more hesitant about using initializer lists
. On some other forums (eg. comp.lang.c++.moderated) there are questions about their behaviour and its possible that they may change closer to the release of the standard.
In Python, this:
my_object.method("foo")
...is syntactic sugar, which the interpreter translates behind the scenes into:
MyClass.method(my_object, "foo")
...which, as you can see, does indeed have two arguments - it's just that the first one is implicit, from the point of view of the caller.
This is because most methods do some work with the object they're called on, so there needs to be some way for that object to be referred to inside the method. By convention, this first argument is called self
inside the method definition:
class MyNewClass:
def method(self, arg):
print(self)
print(arg)
If you call method("foo")
on an instance of MyNewClass
, it works as expected:
>>> my_new_object = MyNewClass()
>>> my_new_object.method("foo")
<__main__.MyNewClass object at 0x29045d0>
foo
Occasionally (but not often), you really don't care about the object that your method is bound to, and in that circumstance, you can decorate the method with the builtin staticmethod()
function to say so:
class MyOtherClass:
@staticmethod
def method(arg):
print(arg)
...in which case you don't need to add a self
argument to the method definition, and it still works:
>>> my_other_object = MyOtherClass()
>>> my_other_object.method("foo")
foo
Best Answer
The problem is that the first argument passed to class methods in python is always a copy of the class instance on which the method is called, typically labelled
self
. If the class is declared thus:it behaves as expected.
Explanation:
Without
self
as the first parameter, whenmyfoo.foodo(thing="something")
is executed, thefoodo
method is called with arguments(myfoo, thing="something")
. The instancemyfoo
is then assigned tothing
(sincething
is the first declared parameter), but python also attempts to assign"something"
tothing
, hence the Exception.To demonstrate, try running this with the original code:
You'll output like:
You can see that 'thing' has been assigned a reference to the instance 'myfoo' of the class 'foo'. This section of the docs explains how function arguments work a bit more.