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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…