pythonpython-3.xclassgetattrsetattr

Not able to setattr using class.__setattr__(key,value)


I have my code like this one:

class __Metadata(type):
    def __init__(cls, name, bases, dict):
        super().__init__(name, bases, dict)
        
   
    def __setattr__(self, key, value):
        super().__setattr__(key, value)
        return

class SimpleData(metaclass=__Metadata):
    pass


class Data1(SimpleData):
    BOOK = "Book1"
    SPORT = "Football"
    OTHER = "Other"

when i try this one:

Data1.__setattr__("FILM", "Avengers")

im getting this error:

TypeError:  expected 2 arguments, got 1

how can i fix this so when i use: Data1.__getattribute__("FILM") i get Avengers


Solution

  • I don't know if you're sharing the full code, but these functions do not relate to each other at all, the setattr question has been asked so many times before..

    You don't need a custom meta class, or SimpleData (while I have no idea what this could do):

    class Data1(object):
        def __init__(self, attr):
            super().__setattr__('attr', dict())
            self.attr = attr
    
        def __getattr__(self, name):
            if name in self.attr:
                return self.attr[name]
            else:
                return 0
    
        def __setattr__(self, key, value):
            if key in self.attr:
                self.attr[key] = value
            else:
                super().__setattr__(key, value)
    
           # return is irrelevant
    
    d = Data1({"book": "Book1"})
    print(d.book)
    # Book1