tags:

views:

8065

answers:

10

I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.

What I'm trying to figure out is:

In a method:

def method(self, blah):
    def __init__(?):
        ....
    ....

What does self do? what is it meant to be? and is it mandatory?

What does the __init__ method do? why is it necessary? etc

I think they might be oop constructs, but I don't know very much..

Thanks in advance

+6  A: 

They are OOP constructs. If you are a beginner in OOP, it's going to be hard to explain them in a few sentences.

Here's a tutorial that introduces OOP in Python. It also provides some answers to your questions:

http://www.voidspace.org.uk/python/articles/OOP.shtml

maxyfc
+1  A: 

You would be correct, they are object-oriented constructs. Basically self is a reference (kind of like a pointer, but self is a special reference which you can't assign to) to an object, and __init__ is a function which is called to initialize the object - that is, set the values of variables etc. - just after memory is allocated for it.

David Zaslavsky
+1  A: 

__init__ does act like a constructor. You'll need to pass "self" to any class functions as the first argument if you want them to behave as non-static methods. "self" are instance variables for your class.

ewalk
+1  A: 

Yep, you are right, these are oop constructs.

init is the constructor for a class. The self parameter refers to the instance of the object (like this in C++).

class Point:
    def __init__(self, x, y):
        self._x = x
        self._y = y

The init method gets called when memory for the object is allocated:

x = Point(1,2)

It is important to use the self parameter inside an object's method if you want to persist the value with the object. If, for instance, you implement the init method like this:

class Point:
    def __init__(self, x, y):
        _x = x
        _y = y

Your x and y parameters would be stored in variables on the stack and would be discarded when the init method goes out of scope. Setting those variables as self._x sets those variables as members of the Point object (accessible for the lifetime of the object).

Cannonade
+20  A: 

In this code:

class A(object):
    def __init__(self):
        self.x = 'Hello'

    def method_a(self, foo):
        print self.x + ' ' + foo

... the self variable represents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object; Python does not. You have to declare it explicitly. When you create an instance of the A class and call its methods, it will be passed automatically, as in ...

a = A()               # We do not pass any argument to the __init__ method
a.method_a('Sailor!') # We only pass a single argument

The __init__ method is roughly what represents a constructor in Python. When you call A() Python creates an object for you, and passes it as the first parameter to the __init__ method. Any additional parameters (e.g., A(24, 'Hello')) will also get passed as arguments--in this case causing an exception to be raised, since the constructor isn't expecting them.

Chris B.
+2  A: 

In short:

  1. self as it suggests, refers to itself- the object which has called the method. That is, if you have N objects calling the method, then self.a will refer to a separate instance of the variable for each of the N objects. Imagine N copies of the variable a for each object
  2. __init__ is what is called as a constructor in other OOP languages such as C++/Java. The basic idea is that it is a special method which is automatically called when an object of that Class is created

HTH, Amit

Amit
+2  A: 

The 'self' is a reference to the class instance

class foo:
    def bar(self):
            print "hi"

Now we can create an instance of foo and call the method on it, the self parameter is added by Python in this case:

f = foo()
f.bar()

But it can be passed in as well if the method call isn't in the context of an instance of the class, the code below does the same thing

f = foo()
foo.bar(f)

Interestingly the variable name 'self' is just a convention. The below definition will work exactly the same.. Having said that it is very strong convention which should be followed always, but it does say something about flexible nature of the language

class foo:
    def bar(s):
            print "hi"
tarn
+1  A: 

This may help: http://homepage.mac.com/s_lott/books/nonprog/htmlchunks/ch42.html

S.Lott
A: 

note that self could actually be any valid python identifier. For example, we could just as easily write, from Chris B's example:

class A(object):
    def __init__(foo):
        foo.x = 'Hello'

    def method_a(bar, foo):
        print bar.x + ' ' + foo

and it would work exactly the same. It is however recommended to use self because other pythoners will recognize it more easily.

TokenMacGuy
A: 

Hello!

I have another question that belong to this subject. I dont know how i initiate a class, class P(): for example. How can i reach a funktion in class P from a class called , class C?

I dont find any good simple example on the webb. It dont need to be effective and goodlooking, i want it to work :)

I tried this in class P def init(self): Thread.init(self)

def(run) for example..run is a simple random loop that i want to run again or start from class C.

kindly Niklas

Niklas Andersson
if you *have another question* you'll need to ask another question. This is not a forum. Please delete this non-answer. Thanks.
SilentGhost