PS.: I will not get into the merit of wether it is recommended to do things that I will exemplify here.
Adding to Bill Lynch's answer
What is "Age" attribute now? I mean is that class attribute or what?
Age is now an instance variable on your instance of sss named object.
PS.: Don't use object
for it is a keyword in python.
What is the value of the "Age" attribute now?
The value is 19.
I mean is that class attribute or what?
It is a attribute of the instance you created from the class, and only for that instance.
how can I add attribute to the class method?
If you want to add the attribute to the class so that every instance has a new attribute of your choosing, you can do this:
setattr(sss, 'b', 'Python')
obj1 = sss("Adam", "Roger")
print(obj1.b)
obj2 = sss("Adam", "Roger")
print(obj2.b)
obj2.b = "New"
print(obj1.b) # will still be Python
print(obj2.b) # now will be New
If you want to overwrite method1 with a new method:
sss_obj = sss("Adam", "Roger")
def method1(self):
self.b = 'New'
setattr(sss, 'method1', method1)
print('Should be False because the instance has no b attribute yet.', hasattr(sss_obj, 'b'))
sss_obj.method1()
print('Now it has and b value is', sss_obj.b)
If you want to change the method on a specific instance of class sss:
sss_obj = sss("Adam", "Roger")
sss_obj2 = sss("Adam", "Roger")
def method1():
sss_obj2.b = 'New'
setattr(sss_obj2, 'method1', method1)
sss_obj.method1()
print('Should be False because method1 from instance sss_obj does not set b.', hasattr(sss_obj, 'b'))
sss_obj2.method1()
print('Now on instance 2 the b value is', sss_obj2.b)
If you want to change the source of the method as a string programatically:
sss_obj = sss("Adam", "Roger")
new_method_source = 'self.b = "NotRecommended"\n' \
'print("Got into changed method")'
def method1(self):
return exec(
compile(new_method_source, '', mode='exec'),
None,
{
'self': self
}
)
setattr(sss, 'method1', method1)
If you want to change the code from method1, first grab the source with the following line
method1_src = inspect.getsource(sss_obj.method1)
Then change the string as you will and do a similar thing as previously mentioned (compile and stuff).
Cheers