Python - Class Definition Syntax

General Form

Class definition is a compound statement, with a body of statements typically indented appearing under the header.

In the header, superclasses are listed in parentheses after the class name, separated by commas.

Listing more than one superclass leads to multiple inheritance.

Here is the statement's general form:

class name(superclass,...):           # Assign to name 
    attr = value                      # Shared class data 
    def method(self,...):             # Methods 
        self.attr = value             # Per-instance data 

Within the class statement, any assignments generate class attributes, and specially named methods overload operators.

For instance, a function called __init__ is called at instance object construction time, if defined.

Demo

class SharedData: 
    test = 42          # Generates a class data attribute 
#  w w  w  .  ja  v a 2s .  c  om
x = SharedData()       # Make two instances 
print( x )
y = SharedData() 
print( y )
print( x.test, y.test )         # They inherit and share 'test' (a.k.a. SharedData.test)

Result

Here, because the name test is assigned at the top level of a class statement, it is attached to the class and so will be shared by all instances.

Related Topic