初始化属性对象类并使其常量

时间:2018-11-13 23:24:08

标签: python python-3.x

我想创建只读属性。 下面的示例效果很好,受https://howto.lintel.in/how-to-create-read-only-attributes-and-restrict-setting-attribute-values-on-object-in-python/

的启发和简化
class Attr1(object):
    def __get__(self, instance, owner):
        return self.value
    def __set__(self, instance, value):
        self.value = int(value)
class Attr2(object):
    def __get__(self, instance, owner):
        return self.value
    def __set__(self, instance, value):
        self.value = int(value)
class AttrFormula(object):
    def __get__(self, instance, owner):
        return instance.attr1 / instance.attr2
class Class(object):
    attr1 = Attr1()
    attr2 = Attr2()
    attrFormula = AttrFormula()

A = Class()
A.attr1 = 1
A.attr2 = 2
print("Class A attr1 =", A.attr1)
print("Class A attr2 =", A.attr2)
print("Class A attrFormula =", A.attrFormula)
B = Class()
B.attr1 = 3
B.attr2 = 3
print("Class B attr1 =", B.attr1)
print("Class B attr2 =", B.attr2)
print("Class B attrFormula =", B.attrFormula)

并输出:

Class A attr1 = 1
Class A attr2 = 2
Class A attrFormula = 0.5
Class B attr1 = 3
Class B attr2 = 3
Class B attrFormula = 1

但是现在,我想更改

A = Class()
A.attr1 = 1
A.attr2 = 2

通过

A = Class(1,2)

因为我要禁用所有的setter属性并使这些属性不可修改。这样的东西:

class Attr1(object):
    def __init__(self, value=None):
        self.value = value
    def __get__(self, instance, owner):
        return self.value
    def __set__(self, instance, value):
        raise AttributeError("You can't change attr1")
class Attr2(object):
    def __init__(self, value=None):
        self.value = value
    def __get__(self, instance, owner):
        return self.value
    def __set__(self, instance, value):
        raise AttributeError("You can't change attr2")
class AttrFormula(object):
    def __get__(self, instance, owner):
        return instance.attr1 / instance.attr2
class Class(object):
    attr1 = Attr1()
    attr2 = Attr2()
    attrFormula = AttrFormula()

    def __init__(self, attr1, attr2):
        self.attr1 = attr1              # ERROR because it calls __set__
        self.attr2 = attr2

A = Class(1,2)
print("Class A attr1 =", A.attr1)
print("Class A attr2 =", A.attr2)
print("Class A attrFormula =", A.attrFormula)
B = Class(5,7)
print("Class B attr1 =", B.attr1)
print("Class B attr2 =", B.attr2)
print("Class B attrFormula =", B.attrFormula)

B.attr1 = 10 # Forbidden, desired error

如何在attr1中初始化attr2Class

0 个答案:

没有答案