1

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 ?

2
  • Yes, I am sorry, my mistake Commented Jan 26, 2016 at 9:30
  • Consider also overriding __repr__ or __str__. Overriding the first special method I mentioned will work everywhere where you will "present" your object eg. in echo in IDLE. Overriding the second one will change behavior of your objects in print function. Commented Jan 26, 2016 at 10:04

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

I don't think this is what the OP wants. And if he create two Common object? They will be declared with different names and the "Obj" in the returned string will not be good anymore.
0

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

2 Comments

Almost there. How do I get the name of the Object as well ?
Actually, there's no straight way to get instance name, unlike class name, because instance name is just a reference to memory block, unlike class name which represents a type. However, it can be done by inspecting the stack with traceback or inspect, i.e. see stackoverflow.com/questions/1690400/…. Though, it's more common to have a name attribute and assign it in constructor when creating an instance, and then use it when needed, i.e. in __repr__ or __str__.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.