gpt4 book ai didi

python - python中是否存在空类?

转载 作者:太空狗 更新时间:2023-10-29 21:15:29 26 4
gpt4 key购买 nike

python中是否存在创建空对象的特殊类?我试过 object(),但它不允许我添加字段。我想像这样使用它:

obj = EmptyObject()
obj.foo = 'far'
obj.bar = 'boo'

我每次(在几个独立的脚本中)都应该像这样定义新类吗?

class EmptyObject:
pass

我用的是python2.7

最佳答案

types.SimpleNamespace是在 Python 3.3 中引入的,正是为了达到这个目的。该文档还展示了一种在 Python 中自己实现它的简单方法,因此您可以将它添加到 Python 3.3 之前的设置中并像它在那里一样使用它(请注意,实际实现是在 C 中完成的):

class SimpleNamespace (object):
def __init__ (self, **kwargs):
self.__dict__.update(kwargs)
def __repr__ (self):
keys = sorted(self.__dict__)
items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
return "{}({})".format(type(self).__name__, ", ".join(items))
def __eq__ (self, other):
return self.__dict__ == other.__dict__

当然,如果您不需要它的一些功能,一个简单的 class Empty: pass 也可以做到同样的事情。

关于python - python中是否存在空类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22509423/

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