简体   繁体   中英

Python class: How to check whether an attribute is defined inside __init__ or outside __init__

So if I have an class like this:

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

Since I need to write a __setattr__ method to modify the attributes (ex. if it was defined inside __init__ then do something; if it was defined outside __init__ do something else. How do I determine if it was declared in init or not?

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

Most of the instance attributes that you define or the parent class (or object) does are going to behave the same and be for the most part indistinguishable. If you really want to distinguish them for whatever reason, you should yourself create a way to identify them, perhaps by using a dictionary instead.

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']

With that said, I am not at all clear about why you want to do this. Maybe you should try looking for a simpler solution to the problem than overriding __setattr__ .

Update:

It seems to me that you're trying to restrict updation of variables, perhaps in your attempt to create "real private variables". In my advice, don't . There's a reason that Python allows you to do a lot of things that might seem insane from point of view of Static languages. You should just start your variables with _ to mark them as private similar to what Python recommends. If people are going to access them anyway, then what's stopping them from finding a workaround to circumvent the "restrictions" that you're trying to enforce? Besides, sometimes there is a genuine justification for accessing private variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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