Does there exist empty class in python?

2020-08-26 05:19发布

问题:

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

回答1:

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.



回答2:

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:

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')


回答4:

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.