Python类:如何检查属性是在初始化内定义的还是在初始化外定义的__

2024-04-19 20:41:16 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有这样一节课:

class A:
    def __init__(self):
        self.a = 1
obj = A()
obj.b = 2

因为我需要编写一个\uuusetattr\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。如何确定它是否在init中声明?你知道吗

def __setattr__(self,name,value):
    if name not in self.__dict__:
        self.__dict__['ABC'+ name] = value # add 'ABC' before attribute's name if it was declared in __init__
    else:
        self.__dict__[name] = value # if it was declared outside __init__ then the attribute name doesn't change

Tags: nameinselfobjifinitvaluedef
1条回答
网友
1楼 · 发布于 2024-04-19 20:41:16

您所定义的或父类(或对象)所做的大多数实例属性的行为都是相同的,并且在很大程度上是不可区分的。如果你真的想把它们区分开来,不管出于什么原因,你应该自己创造一种方法来识别它们,也许可以用字典来代替。你知道吗

class A:
    def __init__(self):
        self.my_variables = {'a': 1}

        # Or maintain a list with their names, it seems ugly however
        self.my_variables = ['a']

话说回来,我一点也不清楚你为什么要这么做。也许您应该尝试寻找一种比重写__setattr__更简单的解决方案。你知道吗

更新:

在我看来,您试图限制变量的更新,也许是为了创建“真正的私有变量”。在我看来,不要。从静态语言的角度来看,Python允许您做很多看起来很疯狂的事情是有原因的。您应该以_开始变量,将它们标记为私有的,类似于Python所建议的。如果人们无论如何都要访问它们,那么是什么阻止了他们找到规避您试图实施的“限制”的解决方法呢?此外,有时访问私有变量是有正当理由的。你知道吗

相关问题 更多 >