Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a python property in __init__

I have a class with an attribute I wish to turn into a property, but this attribute is set within __init__. Not sure how this should be done. Without setting the property in __init__ this is easy and works well

import datetime  class STransaction(object):     """A statement transaction"""     def __init__(self):         self._date = None      @property     def date(self):         return self._date      @date.setter     def date(self, value):         d = datetime.datetime.strptime(value, "%d-%b-%y")         self._date = d  st = STransaction() st.date = "20-Jan-10" 

But once initialization needs to occur in __init__ it gets more complicated and I am not sure of the correct course of action.

class STransaction(object):     """A statement transaction"""     def __init__(self, date):         self._date = None 

Strangely to me, the following seems to work but smells very bad.

class STransaction(object):     """A statement transaction"""     def __init__(self, date):         self._date = None         self.date = date      @property     def date(self):         return self._date      @date.setter     def date(self, value):         d = datetime.datetime.strptime(value, "%d-%b-%y")         self._date = d 

What is the correct way to go about setting properties in __init__?

Thanks, Aaron.

like image 323
Aaron Barclay Avatar asked Oct 15 '10 11:10

Aaron Barclay


People also ask

How do you initialize a property in Python?

Use the __init__() method to initialize the object's attributes. The __init__() doesn't create an object but is automatically called after the object is created.

What is __ init __ () in Python?

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.

How do you create a class property in Python?

Python property() function returns the object of the property class and it is used to create property of a class. Parameters: fget() – used to get the value of attribute. fset() – used to set the value of attribute.


2 Answers

I do not see any real problem with your code. In __init__, the class is fully created and thus the properties accessible.

like image 119
Florian Mayer Avatar answered Sep 30 '22 18:09

Florian Mayer


class STransaction(object):     """A statement transaction"""     def __init__(self, date):         self._date = None #1         self.date = date  #2 

If you want to set the proxy field self._date without executing of your setter use the #1 line. If you would like to execute the setter at startup too use the #2. Both ways are correct, it's just a matter of what do you want to do.

like image 26
Mariusz Jamro Avatar answered Sep 30 '22 18:09

Mariusz Jamro