Python: Class and Object

By Xah Lee. Date: . Last updated: .

Define a Class

A class is a boxed set of functions and variables. It defines a blueprint, of what variable and functions is together as a single thing.

Define a class like this:

# define a class
class X1:
    "A class example"

    ii = 1 # a class variable

    # define a method. There MUST have a “self” in the arg spec as first item.
    # this method takes no argument.
    def ff(self):
        return 3

By convention, class name starts with a cap letter.

Instantiate a Class, Create a Object

Class is just a blueprint of structure. Class is useless by itself, in the same way a function is useless if you don't call it.

You need to create a instance of the class to actually do something. Instance of a Class is called Object.

# example of a class, and create a instance of it

# define a class
class X1:
    "A class example"

    ii = 1  # a class variable

    # This method defines 1 parameter, the x.
    def gg(self, x):
        return x + 1

# create a object of the class X1
# This is called “instantiating a class”.
xx = X1()

# Data or functions defined in a class are called the class's attributes or methods.
# To access them, append a dot and their name after the object's name.

# access a class variable
print(xx.ii)
# 1

# call a method
print(xx.gg(4))
# 5

Define Constructor

You can define a method in a class such that it'll be automatically called when the class is instantiated. Such a method is called constructor. (aka initializer)

# example of a constructor

class YY:
    "A class example"

    # method named __init__ is special
    # __init__ is automatically called whenever a class is instantiated.
    # this method is called constructor
    # by convention, this is placed at top of method def in a class
    def __init__(self):
        print("constructor called")

    # some other method
    def gg(self, n):
        return n + 1

xx = YY()
# prints:
# constructor called

Class variable and Instance variable

In python, initially, the class variable are shared among all instances, but each instance can set value to class variable and has its own value.

Here's a example class variable and 2 instances accessing them.

# each instance share the class variable initially, but as soon as they set value, they have own copy

# define a class
class CC:
    "A class example"

    ii = 1 # a class variable

m1 = CC()
m2 = CC()

# all the following prints True

# each instance share the class variable initially
print(m1.ii == 1) # True
print(m2.ii == 1) # True

# you can set the class variable for all instances
CC.ii = 2
print(m1.ii == 2)
print(m2.ii == 2)

# instance variable can be change its class variable like this
m1.ii = 3
m2.ii = 4

print(m1.ii == 3)
print(m2.ii == 4)

# once intance set their own values of the class variable,
# changing the class variable has no effect on the instance's values
CC.ii = 5
print(m1.ii == 3)
print(m2.ii == 4)

Instance variable

To have true instance variable, declare them inside constructor, with self. prefix on the variable.

# true instance variable example

class CC:
    "A class example"

    def __init__(self, x):
        # instance variable
        self.jj = x

    def put(self, x):
        self.jj = x

    def get(self):
        return self.jj

# this has no effect
CC.jj = 22222

m1 = CC(7)
m2 = CC(8)

# all the following print True

print(m1.jj == 7)
print(m1.get() == 7)

print(m2.jj == 8)
print(m2.get() == 8)

m1.put(3)
print(m1.get() == 3)

m2.put(4)
print(m2.get() == 4)

Extending a Class, Inheritance

A class can be extended. If a class X2 extends class X1, then class X2 will automatically have all the attributes (the variable and functions) of X1.

# example of extending a class. inheritance

class X1:
    "A class example"

    def ff(self):
        return "ff"

# extending a class by putting parent in the parenthesis.
class X2(X1):
    "X2 extends/inherits X1"

    def gg(self, x):
        return x + 2

# create a object of X2
x2 = X2()

# ff is from X1. a inherited method
print(x2.ff())
# ff

Default Attributes for Class

Python defines the following class members by default:

__dict__
A dictionary of attributes of the object.
__doc__
Doc string of the object, or None
__name__
Name of the class
__module__
Module name in which the class is defined. If top level, it's "__main__"
__bases__
A tuple of parent classes. May be empty.

Example:

class X1:
    "A class example"

    ii = 1

    def ff(self):
        return 3

    def gg(self, x):
        return x + 1

    def __init__(self,x):
        self.jj = x

print(X1.__dict__)

# sample output:
# {
#  'gg': <function gg at 0x1d8d6e0>,
#  '__module__': '__main__',
#  'ii': 1,
#  'ff': <function ff at 0x1d8d668>,
#  '__doc__': 'A class example',
#  '__init__': <function __init__ at 0x1d8d758>
# }

Useful Functions on Object

The following are useful functions on objects.

getattr[obj, name]
Return the value of a attribute.
hasattr[obj, name]
Check if attribute exist.
setattr[obj, name, val]
Set a attribute.
delattr[obj, name]
Delete a attribute.
issubclass(a, b)
Return true if a is a subclass of b.
isinstance(obj, class)
Return true if obj is a instance of class.

Python Function and Class