Basic Python Query

Steven D'Aprano steve at pearwood.info
Wed Aug 21 04:19:28 EDT 2013


On Wed, 21 Aug 2013 14:50:20 +0800, chandan kumar wrote:

[...]
> 1.Difference between  def StartThread(self) and def __init__(self):

__init__ is a special method called automatically by Python when you 
create an instance. StartThread is a method that the author of the code 
(perhaps you?) wrote themselves. It has no special meaning in Python, it 
will do whatever it is programmed to do, but only if you call it.


> 2   instance = Test() ,when this is called ,the code flow goes inside 
> the threading module , But 
>      instance1= Test1() ,the code flow goes inside the class Test1
>      When we call the both classes in same way ,How does the flow is 
> different for both.


When Test() is called, a new Test instance is created, and the __init__ 
method is called, but the thread is not started.

When you call Test1(), the __init___ method automatically starts the 
thread, because it includes the line "self.start()".

(Although, in the code you show, the indentation is wrong and the code 
will not work correctly. Please be more careful in the future about the 
indentation.)


> 3. Lets say self is passed explicitly for all the methods Like
>     def method1(self)
>          method2()

That won't work, you need to say self.method2()


>    def  method2(self):
>          method3()
>    def method(self)
>         method4()
>    def method4(self)
>
> What does self holds in method4 ,Is it self argument from method1?
> Sorry i'm confused with self argument.Please clarify if its valid
> question.

Yes, it is the same "self" all the way through. If you have ordinary 
functions:

def f1(x):
    f2(x)

def f2(y):
    f3(y)

def f3(z):
    print z

and you call f1("something"), then the result will be to print 
"something". Even though the argument name is different, the same 
argument is passed from one function to the next.

Methods are exactly the same, except that the "self" argument is nearly 
always called "self".

When you have an instance, and you call one of its methods:

instance = SomeClass()
instance.method(extra, args)

then Python automatically uses the instance as the "self" argument. This 
is equivalent to:

SomeClass.method(instance, extra, args)
# inside the method, self=instance


except Python does it for you, instead of you needing to write it out in 
full like that. 



-- 
Steven



More information about the Python-list mailing list