无法使用 class.__setattr__(key,value) 设置属性

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

我有这样的代码:

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"

当我尝试这个时:

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

我收到此错误:

TypeError:  expected 2 arguments, got 1

我该如何解决这个问题,所以当我使用时:Data1.__getattribute__("FILM") 我得到了复仇者联盟

我不知道你是否分享了完整的代码,但是这些函数之间根本没有关系,setattr这个问题已经被问过很多次了..

您不需要自定义元 class 或 SimpleData(虽然我不知道这能做什么):

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