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 structure or blueprint, of what variable and functions is together as a single thing.

Define a class like this:

# -*- coding: utf-8 -*-
# python

# define a class.
# by convention, class name starts with a cap letter
class X1:
    "A class example"

    ii = 1 # a class variable

    # define a method. There MUST always be a 「self」 in the arg spec as first item.
    # this method takes no argument.
    def ff(self):
        return 3

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

# -*- coding: utf-8 -*-
# python

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

# -*- coding: utf-8 -*-
# python

# 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 "i'm constructor! i'm called."

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

xx = YY()
# prints:
# i'm constructor! i'm 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.

# -*- coding: utf-8 -*-
# python

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

# each instance share the class variable initially
print m1.ii # 1
print m2.ii # 1

# 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

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.

# -*- coding: utf-8 -*-
# python

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

# -*- coding: utf-8 -*-
# python

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 by Example

  1. Python Basics
  2. Print Version String
  3. Builtin Help
  4. Quote String
  5. String Operations
  6. String Methods
  7. Format String
  8. True, False
  9. if then else
  10. for, while, Loops
  11. List Basics
  12. Loop Thru List
  13. Map Function to List
  14. List Comprehension
  15. List Methods
  16. Dictionary
  17. Loop Thru Dict
  18. Dict Methods
  19. Function
  20. Class
  21. List Modules
  22. Write a Module
  23. Unicode 🐍

Regex

  1. Regex Basics
  2. Regex Reference

Text Processing

  1. Read/Write File
  2. Traverse Directory
  3. Manipulate 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
  5. Check Page Load Size
  6. Thumbnail Generation

Misc

  1. JSON
  2. Find Script Path
  3. Get Env Var
  4. System Call
  5. Decompress Gzip
  6. Complex Numbers

Advanced

  1. Sort
  2. Copy Nested List
  3. Tuple vs List
  4. Sets, Union, Intersection
  5. Closure in Python 2
  6. Decorator
  7. Append String in Loop
  8. Timing f timeit
  9. Keyword Arg Default Value Unstable