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:
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
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 executedwithout
__init__
functionhello.py:
class def: a=2136 print
test.py:
from hello import def def def(): b=7 print b if __name__=='__main__': def()
output:
2136 7
with
__init__
function definedhello.py:
class def: def __init__(self): a=2136 print
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
Post a Comment