[英]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__
.我有一个类的属性,我希望将其转换为
property
,但该属性是在__init__
设置的。 Not sure how this should be done.不知道这应该怎么做。 Without setting the property in
__init__
this is easy and works well无需在
__init__
设置属性,这很容易并且运行良好
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.但是一旦需要在
__init__
初始化,它就会变得更加复杂,我不确定正确的操作过程。
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__
?在
__init__
设置属性的正确方法是什么?
Thanks, Aaron.谢谢,亚伦。
I do not see any real problem with your code.我没有看到您的代码有任何实际问题。 In
__init__
, the class is fully created and thus the properties accessible.在
__init__
,类是完全创建的,因此属性是可访问的。
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.如果您想设置代理字段
self._date
而不执行您的设置器,请使用 #1 行。 If you would like to execute the setter at startup too use the #2.如果您也想在启动时执行 setter,请使用 #2。 Both ways are correct, it's just a matter of what do you want to do.
两种方式都是对的,只是看你想做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.