Does there exist empty class in python?

2020-08-26 05:42发布

Does there exist special class in python to create empty objects? I tried object(), but it didn't allow me to add fields. I want to use it like this:

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

Should I each time(in several independent scripts) define new class like this?

class EmptyObject:
    pass

I use python2.7

4条回答
够拽才男人
2楼-- · 2020-08-26 05:45

If you are looking for a place holder object to which you can add arbitrary static members, then the closest I got is an empty lambda function.

obj = lambda: None    # Dummy function
obj.foo = 'far'
obj.bar = 'boo'

print obj.foo, obj.bar
# far boo

Remember: obj is not an object of a class, object doesn't mean class instance, because in Python classes and functions are objects at runtime just like class instances

查看更多
何必那么认真
3楼-- · 2020-08-26 05:56

There is no types.SimpleNamespace in Python 2.7, you could use collections.namedtuple() for immutable objects instead:

>>> from collections import namedtuple
>>> FooBar = namedtuple('FooBar', 'foo bar')
>>> FooBar('bar', 'foo')
FooBar(foo='bar', bar='foo')

Or argparse.Namespace:

>>> from argparse import Namespace
>>> o = Namespace(foo='bar')
>>> o.bar = 'foo'
>>> o
Namespace(bar='foo', foo='bar')
查看更多
beautiful°
4楼-- · 2020-08-26 05:59

You can create a new type dynamically with the fields you want it to have using the type function, like this:

x = type('empty', (object,), {'foo': 'bar'})
x.bar = 3
print(x.foo)

This is not entirely what you want though, since it will have a custom type, not an empty type.

查看更多
Lonely孤独者°
5楼-- · 2020-08-26 06:02

types.SimpleNamespace was introduced with Python 3.3 to serve this exact purpose. The documentation also shows a simple way to implement it yourself in Python, so you can add it to your pre-Python 3.3 setup and use it as if it was there (note that the actual implementation is done in 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__

But of course, if you don’t need its few features, a simple class Empty: pass does just the same.

查看更多
登录 后发表回答