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 ?

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
user1530405
  • 447
  • 1
  • 8
  • 16
  • Yes, I am sorry, my mistake – user1530405 Jan 26 '16 at 09: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. – PatNowak Jan 26 '16 at 10:04

2 Answers2

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
gtlambert
  • 11,711
  • 2
  • 30
  • 48
  • 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. – k4ppa Jan 26 '16 at 09:56
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

Nikita
  • 6,101
  • 2
  • 26
  • 44
  • Almost there. How do I get the name of the Object as well ? – user1530405 Jan 26 '16 at 20:48
  • 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 http://stackoverflow.com/questions/1690400/getting-an-instance-name-inside-class-init. 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__`. – Nikita Jan 27 '16 at 06:36