如何限制在构造函数之外设置属性? [英] How to restrict setting an attribute outside of constructor?

查看:18
本文介绍了如何限制在构造函数之外设置属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想禁止在类的某些属性初始化后进一步赋值.例如;在 Person 实例 'p' 初始化之后,没有人可以明确地为 'ssn'(社会安全号码)属性分配任何值._setattr__init_ 方法内部赋值时也被调用,因此它不是什么我想要.我只想限制更多的分配.我怎样才能做到这一点?

I want to forbid further assignments on some attributes of a class after it was initialized. For instance; no one can explicitly assign any value to 'ssn' (social security number) property after the Person instance 'p' has been initialized. _setattr_ is also being called while assigning the value inside _init_ method, thus it is not what I want. I'd like to restrict only further assignments. How can I achieve that?

class Person(object):
    def __init__(self, name, ssn):
        self.name = name
        self._ssn = ssn

    def __setattr__(self, name, value):
        if name == '_ssn':
            raise AttributeError('Denied.')
        else:
            object.__setattr__(self, name, value)

>> p = Person('Ozgur', '1234')
>> AttributeError: Denied.

推荐答案

通常的方法是使用以下划线开头的私有"属性,以及用于公共访问的只读属性:

The usual way is to use a "private" attribute starting with an underscore, and a read-only property for public access:

import operator

class Person(object):
    def __init__(self, name, ssn):
        self.name = name
        self._ssn = ssn
    ssn = property(operator.attrgetter("_ssn"))

请注意,这并不会真正阻止任何人更改属性 _ssn,但是领先的 _ 证明该属性是私有的.

Note that this does not really hinder anybody to change the attribute _ssn, but the leading _ documents that the attribute is private.

这篇关于如何限制在构造函数之外设置属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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