Search code examples
pythonpython-2.7propertiessettergetter-setter

different setters for python properties


I have a class

class Animal:
    def __init__(self, name='', num_of_owners=0, sleep=0):
        self.name = name
        self.num_of_owners = int(float(num_of_owners))
        self.sleep = float(sleep)

let's say I'm reading all the properties from some file.

I'm using Properties for getters and setters.

@property
def name(self):
    return self.name

@name.setter
def name(self, value):
    self.name = value

now when reading from the file, I don't want to look for every property in the dictionary i got specifically.

So i can run a for over the dictionary and type

for name, value in animal_props.iteritems():
     setattr(animal, name, value)

but then all the properties are set as strings. The thing is I have about 8 properties some floats some int some strings.

Anyway to run this for, and not make regular setters and run a specific setter for each property.

example:

class Animal:
    def __init__(self, name='', num_of_owners=0, sleep=0):
        self._name = name
        self._num_of_owners = int(float(num_of_owners))
        self._sleep = float(sleep)

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

    @property
    def num_of_owners(self):
        return self._num_of_owners

    @num_of_owners.setter
    def num_of_owners(self, value):
        self._num_of_owners = int(value)

    @property
    def sleep (self):
        return self._sleep

    @sleep.setter
    def sleep(self, value):
        self._sleep = int(float(value))

d = {'name': 'doggy', 'num_of_owners': '3', 'sleep': '5.643'}
dog = Animal()
for name, value in d.iteritems():
    setattr(dog, name, value)

print type(dog.sleep)

I need the type at the end to be float. since i will later use it as a float.

Creating separate 'ifs' and send to each setter is fine, but is there anyway to do it with just that one for.


Solution

  • You are using python 2 with old-style classes. Properties are only available with new-style classes:

    class Animal(object):
        ...