How to set a python property in __init__

后端 未结 2 1416
星月不相逢
星月不相逢 2020-12-15 03:41

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 th

相关标签:
2条回答
  • 2020-12-15 04:08
    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.

    0 讨论(0)
  • 2020-12-15 04:14

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

    0 讨论(0)
提交回复
热议问题