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 Xa:
    "A class example"

    ii = 1  # a class variable

    # define a method.
    # first parameter must must be “self”.
    # other parameters are the actual parameters for the method.
    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 Xa:
    "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 Xa
# This is called “instantiating a class”.
xx = Xa()

# 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 Cat:
    "A class example"

    # method named __init__ is special
    # __init__ is automatically called whenever a class is instantiated.
    # __init__ is called a “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 = Cat()
# 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 Xclass:
    "A class example"

    ii = 1 # a class variable

object_a = Xclass()
object_b = Xclass()

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

# you can set the class variable for all instances
Xclass.ii = 2
print(object_a.ii == 2) # True
print(object_b.ii == 2) # True

# instance variable can change its class variable like this
object_a.ii = 3
object_b.ii = 4

print(object_a.ii == 3) # True
print(object_b.ii == 4) # True

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

Instance variable

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

# true instance variable example

class Xdog:
    "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
Xdog.jj = 22222

aa = Xdog(7)
bb = Xdog(8)

print(aa.jj == 7)  # True
print(aa.get() == 7)  # True

print(bb.jj == 8)  # True
print(bb.get() == 8)  # True

aa.put(3)
print(aa.get() == 3)  # True

bb.put(4)
print(bb.get() == 4)  # True

Extending a Class, Inheritance

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

# example of extending a class. inheritance

class Xa:
    "A class example"

    def ff(self):
        return "ff"

# extending a class by putting parent in the parenthesis.
class Xb(Xa):
    "Xb extends Xa"

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

# create a object of Xb
x2 = Xb()

# ff is from Xa. 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. (a class can inherit from multiple classes. when method names clash, the it search the left most base class first declared in the parameters of the class definition. )

Example:

class Xa:
    "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(Xa.__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