Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does there exist empty class in python?

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

like image 245
sbeliakov Avatar asked Mar 19 '14 14:03

sbeliakov


People also ask

Can we have empty class in Python?

In Python, to write an empty class pass statement is used. pass is a special statement in Python that does nothing. It only works as a dummy statement. However, objects of an empty class can also be created.

Can a class be empty?

Empty class: It is a class that does not contain any data members (e.g. int a, float b, char c, and string d, etc.) However, an empty class may contain member functions.

What is the size of empty class in Python?

It returns 104 on my machine.

What is an empty object in Python?

Python object() FunctionThe object() function returns an empty object. You cannot add new properties or methods to this object. This object is the base for all classes, it holds the built-in properties and methods which are default for all classes.

What is the size of empty class?

Size of an empty class is not zero. It is 1 byte generally. It is nonzero to ensure that the two different objects will have different addresses. See the following example.

Why do we need empty class?

These properties allow to hold data, methods etc. Empty class that doesn't inherit any base class would be useful as placeholder. On the other hand, empty classes that inherit other classes is a very common pattern. Specially when defining user exceptions.


1 Answers

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

See also, How can I create an object and add attributes to it?

like image 59
jfs Avatar answered Oct 29 '22 08:10

jfs