Hello i have this code
class Test(object):
def start_conn(self):
pass
def __init__(self):
self.conn = start_conn()
But this code make this error:
NameError: global name 'start_conn' is not defined
If i write self.conn = self.start_conn() the program works without error, my question is, is a must to call with self the methods of the class when i’m creating a new instance? or is a desgin error from my side?
Thanks a lot
In short, it’s a must. You have to refer to the container in which the methods are stored. Most of the time that means referring to
self.The way this works is as follows. When you define a (new-style) class
you create a
typeobject that contains the method in its unbound state. You can then refer to that unbound method via the name of the class (i.e. viaFooClass.my_method); but to use the method, you have to explicitly pass aFooClassobject via theselfparameter (as inFooClass.my_method(fooclass_instance, arg)).Then, when you instantiate your class (
f = FooClass()), the methods ofFooClassare bound to the particular instancef.selfin each of the methods then refers to that instance (f); this is automatic, so you no longer have to passfinto the method explicitly. But you could still doFooClass.my_method(f, arg); that would be equivalent tof.my_method(arg).Note, however, that in both cases,
selfis the container through which the other methods of the class are passed tomy_method, which doesn’t have access to them through any other avenue.