Reputation: 455
I have a class
which is instantiated into an object. I would like to be able to generate a string, when I change any of the object's property. The string must contain the objects Name, the property's Name and the value that it changed to:
class Common(object):
pass
Obj = Common()
Obj.Name = 'MyName'
Obj.Size = 50
print Obj.Size
>50
Obj.Size = 100
I would like to have a string containing "Obj,Size,100" Is this possible ?
Upvotes: 1
Views: 1100
Reputation: 6341
Are you looking for special methods, namely __setattr__()
to perform actions on attribute change, i.e.:
>>> class Common(object):
... pass
... def __setattr__(self, name, value):
... print("Name: {}, Value: {}".format(name, value))
... object.__setattr__(self, name, value)
...
>>> obj=Common()
>>> obj.test=10
Name: test, Value: 10
This way anytime you add some attribute to object it'll be printed. See docs for more information: https://docs.python.org/3.5/reference/datamodel.html
Upvotes: 0
Reputation: 11971
You could use a get_size
class method as follows:
class Common(object):
def get_size(self):
return "Obj,Size,{}".format(self.size)
obj = Common()
obj.name = 'MyName'
obj.size = 50
print(obj.get_size())
Output
Obj,Size,50
Upvotes: 1