繁体   English   中英

python中类初始化的最佳实践

[英]Best practice of class initialization in python

嗨,我想知道最佳实践是在python中初始化类,同时确保我的属性具有正确的数据类型。

我应该使用默认值初始化类属性还是调用检查功能?

class Foo:
    # Call with default value
    def __init__(self, bar=""):
         self._bar = bar

    # Calling set-function
    def __init__(self, bar):
        self._bar = ""
        self.set_bar(bar)

    def get_bar(self):
        return self._bar

    def set_bar(self, bar):
        if not isinstance(bar, str):
            raise TypeError("bar must be string")
        self._bar = bar

    def del_bar(self):
        self._bar = ""

    bar = property(get_bar, set_bar, del_bar, 'bar')

您可以尝试以下代码片段:

class Foo:

    def __init__(self, bar=''):
        self.bar = bar

    @property
    def bar(self):
        return self._bar

    @bar.setter
    def bar(self, bar):
        if isinstance(bar, str):
            self._bar = bar
        else:
            raise TypeError('<bar> has to be of type string')

f = Foo('5') # works fine
g = Foo(5) # raises type error

即使在类实例化时未提供任何参数,也将执行检查。 因此,即使您提供一个整数作为默认参数,它也会触发异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM