Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

This my code:

class C:

    def __init__(self):

        self.a = 1

        self.b = 2

    def __setattr__(self,name,value):

       if a in self.__init__:  #Determine if a is an instance of __init__ function

           do something

The above code is returning an error:

    if name in self.__init__:

TypeError: argument of type 'method' is not iterable

If I don't iterate through the self.__init__ function, then how am I supposed to know what attributes are defined in the self.__init__ function?

If the attribute is set in the init, I want to set name prefixed by "somestring_" and append it to the self__dict__: e.g., if I print the self.__dict__ after self.__setattr__, it will print {'somestring_a': 1, 'somestring_b': 2} 

1 Answer

0 votes
by (36.8k points)

Add the attribute that lists an attribute that is set in __init__, and use it.

class C:

    predefined = ['a', 'b']

    def __init__(self):

        self.a = 1

        self.b = 2

    def __setattr__(self,name,value):

        if name in self.predefined:

            do something

        else:

            do something else

Another option would be to copy keys of the self.__dict__ at end of your __init__ method:

class C:

    def __init__(self):

        self.a = 1

        self.b = 2

        self.predefined = set(self.__dict__)

    def __setattr__(self,name,value):

        if name in self.predefined:

            do something

        else:

            do something else

Do you wish to learn Data Science from scratch? Enroll in this Data Scientist

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...