5

What is a "Pythonic" way to define a class that does not need any constructor parameters?

class MyClass:

    # class body

or do we need an explicit constructor? i.e.

class MyClass:
    def __init__:
        pass

    # class body
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Tomasz Bartkowiak
  • 12,154
  • 4
  • 57
  • 62

1 Answers1

7

Your first approach is good enough, unless you want to only use class attributes and not instance attributes
Also every class in Python inherits from object, as explained in detail here

class MyClass:
    pass

An example of such classes might be as follows

  • A class to store multiple class attributes
class MyClass:

    a = 1
    b = 2

print(MyClass.a)
#1
print(MyClass.b)
#2
  • A custom exception where the constructor is implicitly taken from the base class
class MyException(Exception):

    pass

raise MyException
#    raise MyException
#__main__.MyException
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40