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:

# python 3

# 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”.

# python 3

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

# python 3

# 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.

# python 3

# 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.

# python 3

# 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.

# python 3

# 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:

Example:

# python 3

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.

If you have a question, put $5 at patreon and message me.

Python

  1. Python 3 Basics
  2. Python 2 Basics
  3. Python 2 and 3 Difference
  4. Print Version
  5. Builtin Help
  6. Quote String
  7. String Methods
  8. Format String
  9. Operators
  10. Complex Numbers
  11. True, False
  12. if then else
  13. Loop
  14. List Basics
  15. Loop Thru List
  16. Map f to List
  17. Copy Nested List
  18. List Comprehension
  19. List Methods
  20. Sort
  21. Dictionary
  22. Loop Thru Dict
  23. Dict Methods
  24. Tuple
  25. Sets
  26. Function
  27. Closure
  28. 2 Closure
  29. Decorator
  30. Class
  31. Object, ID, Type
  32. List Modules
  33. Write a Module
  34. Unicode 🐍

Regex

  1. Regex Basics
  2. Regex Reference

Text Processing

  1. Read/Write File
  2. Traverse Directory
  3. File Path
  4. Process Unicode
  5. Convert File Encoding
  6. Find Replace in dir
  7. Find Replace by Regex
  8. Count Word Frequency

Web

  1. Send Email
  2. GET Web Page
  3. Web Crawler
  4. HTTP POST

Misc

  1. JSON
  2. Find Script Path
  3. Get Env Var
  4. System Call
  5. Decompress Gzip
  6. Append String in Loop
  7. Timing f timeit
  8. Keyword Arg Default Value Unstable
  9. Check Page Load Size
  10. Thumbnail Generation