简体   繁体   English

从__init __()设置Python属性

[英]Setting a Python property from __init__()

I want to define a class that ensures some constraints when a property is set/modified. 我想定义一个在设置/修改属性时确保某些约束的类。 Furthermore, I want to be able to set the property value on construction, with the same constraints. 此外,我希望能够在具有相同约束的情况下在构造上设置属性值。 Simplified example: 简化示例:

class MyClass(object):
    def __init__(self, attrval):
        self.myattr = attrval

    @property
    def myattr(self):
        return self._myattr

    @myattr.setter
    def myattr(self, value):
        if value is None:
            raise ValueError("Attribute value of None is not allowed!")
        self._myattr = value

I'm calling the property setter right from init (), so the property is the only place where self._myattr is accessed directly. 我直接从init ()调用属性设置器,因此该属性是直接访问self._myattr的唯一位置。 Are there any problems or caveats in using a property like this (like a missing or invalid creation of _myattr)? 使用这样的属性(例如_myattr的丢失或无效创建)是否有任何问题或警告? Maybe when (multiple) inheritance comes in? 也许什么时候(多重)继承? Is there a PEP or some other "official" statement about how to properly initialize properties from init ()? 是否存在有关如何从init ()正确初始化属性的PEP或其他“官方”声明?

Most property examples I found do not use the property setter from the constructor. 我发现的大多数属性示例都不使用构造函数中的属性设置器。 In How to set a python property in __init__ , the underlying attribute gets created explicitly before setting the property. 如何在__init__中设置python属性中 ,将在设置属性之前显式创建基础属性。 Some people think that each single attribute must be explicitly initialized in init (), that's why my code example feels a bit odd. 有人认为每个属性都必须在init ()中显式初始化,这就是为什么我的代码示例有些奇怪。

There won't be any problems. 不会有任何问题。 Use what works for you. 使用对您有用的东西。

One thing to keep in mind is that setting the attribute using the setter runs the validation you've set up. 要记住的一件事是,使用setter设置属性会运行您已设置的验证。 Setting the attribute directly in the __init__ won't have that validation executed. 直接在__init__设置属性不会执行该验证。 This would make the setter version more slower, but safer as per disallowing certain values. 这将使setter版本更慢,但由于不允许使用某些值而更加安全。

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

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