如何在 __init__ 中设置 python 属性 [英] How to set a python property in __init__

查看:37
本文介绍了如何在 __init__ 中设置 python 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类的属性,我希望将其转换为 property,但该属性是在 __init__ 中设置的.不知道这应该怎么做.无需在 __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"

但是一旦需要在 __init__ 中进行初始化,它就会变得更加复杂,我不确定正确的操作过程.

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

__init__ 中设置属性的正确方法是什么?

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

谢谢,亚伦.

推荐答案

我看不出您的代码有任何实际问题.在 __init__ 中,类已完全创建,因此属性可访问.

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

这篇关于如何在 __init__ 中设置 python 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆