gpt4 book ai didi

Python new-style-class相关问题

转载 作者:太空宇宙 更新时间:2023-11-04 01:39:44 27 4
gpt4 key购买 nike

我是一名 Python 学习者,目前正在编写一个字段数量可变的类,如 "Bunch of Named Stuff" example here 中所示。 .

class Bunch:
def __init__(self, **kwds):
self.__dict__.update(kwds)

我还想在这个类中写一个__setattr__ 来检查输入的属性名。但是,python documentation说,

If __setattr__() wants to assign to an instance attribute, it should not simply execute "self.name = value" -- this would cause a recursive call to itself. Instead, it should insert the value in the dictionary of instance attributes, e.g., "self.__dict__[name] = value". For new-style classes, rather than accessing the instance dictionary, it should call the base class method with the same name, for example, "object.__setattr__(self, name, value)".

在那种情况下,我是否也应该在 __init__ 函数中使用 object.__dict__ 来替换 self.__dict__

最佳答案

你可以使用

class Bunch:
def __init__(self, **kwds):
self.__dict__.update(kwds)

def __setattr__(self, name, value):
#do your verification stuff
self.__dict__[name] = value

或使用新式类:

class Bunch(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)

def __setattr__(self, name, value):
#do your verification stuff
super(Bunch, self).__setattr__(name, value)

关于Python new-style-class相关问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6305640/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com