Dynamically add attribute of a class is very easy in python. And it is useful to know.
Here I have a class named Arithmetic, now I want to add functionality of this class named addNum which perform add two number.
Lets see the example
Dynamic code execution is very important in some cases. Sometimes we need to generate code dynamically and then run it.
Lets see a very simple example using exec:
v=5
code = """def myFun():
global v
v=10
print 'This is my function'
"""
exec code
print v
myFun() #must execute the code before calling function
print v
Sometimes we need to make class public and private also.
Lets see python syntex how to do it
#privateClassSample.py
class MyClass():
def myPublicFunction(self):
print "I am public function"
def __myPrivateFunction(self):
print "I am private function"
class _MyPrivateClass():
def myPrivateFunction(self):
print "I am private function of class _MyPrivateClass"
#test.py
from privateClassSample import *
a=MyClass()
a.myPublicFunction()
#b=_MyPrivateClass() # this willl not work, _MyPrivateClass is private class
Sometimes we need to make some private and public function for a class.
Lets see python syntex for such class
#publicVsPrivate.py
class MyClass():
def myPublicFunction(self):
print "I am public function"
def __myPrivateFunction(self):
print "I am private function"
myClass= MyClass()
myClass.myPublicFunction()
#myClass.__myPrivateFunction # This is will not work, __myPrivateFunction private method
Both meythod have some similarities, we can use them without instantiate the object.
Static method know nothing about class and class method knows.
Lets go to a example code:
#staticVsClassMethod.py
class MyClass():
def anyFunction(self):
print "I am any function"
@staticmethod
def myStaticFunction():
print "I am static method"
@classmethod
def myClassFunction(cls):
print "I am class method"
print cls
MyClass.myStaticFunction()
MyClass.myClassFunction()
#MyClass.anyFunction() #this is not possible, need a object instance
Output:
I am static method
I am class method
__main__.MyClass
Sometimes we need to extend an existing class, lets do it some python way
#speak.py
class Speak(object):
def __init__(self,tone):
self.tone = tone
def getTone(self):
print self.tone
#anyName.py
from speak import Speak
class Bird(Speak):
def __init__(self,birdTone):
#construct super class
Speak.__init__(self,birdTone)
class Cow(Speak):
def __init__(self,cowTone):
#another way to construct super class
super(Cow, self).__init__(cowTone)
bird= Bird("Bird Talk")
bird.getTone()
cow= Cow("Cow Talk")
cow.getTone()