Classes and functions in Python -


while writing code on classes , functions,i took case of function , class same name

code executed as:

$python test.py 

to attempted 2 scenarios:

  1. i first wrote them in 1 file test.py , got function gets called rather class

    class abc:     def __init__(self):         a=3         print  def abc():     b=7     print b  if __name__=='__main__':     abc() 

    output:

    7 
  2. i wrote function in 1 file test.py , class of same name in file , imported it.when did not write __init__ function, both function class got executed, while when wrote __init__ function, function got executed

    • without __init__ function

      1. hello.py:

        class def:     a=2136     print 
      2. test.py:

        from hello import def      def def():         b=7         print b  if __name__=='__main__':     def() 

      output:

      2136                                                        7 
    • with __init__ function defined

      1. hello.py:

        class def:     def __init__(self):     a=2136     print 
      2. test.py

        from hello import def  def def():     b=7     print b if __name__=='main':     def() 

      output:

      7 

the body of class executed when class defined. thus, following always prints 2136 when python loads file:

class def:     a=2136     print 

python has create class definition named def, , executes body of class if function. local names function form class body.

this happens regardless of replacing name function. run once; if module has been imported before top-level code not executed again.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -