Python Class

What is a python class

Python class is two different things. It a container and create object containers. They also have methods. What a method. A method is a function wrap into class namespace. It will normally effect or be effect by container. All this will help you organize your code better.

Quick Overview

class Point: # our class name
    string = 'Point'  # class variable. Not an object variable

    # This will create are object and initalize it.
    def __init__(self, x, y):
        c = x + y   # local variable
        self.x = x  # object variable
        self.y = y  # object variable

    def add(self, point): # object method. located in class namespace
        return Point(self.x + point.x, self.y + point.y)

point = Point(2, 3) # object creation. calls __init__ method.

Class Container

Class container holds it own variables. These class variables are like global variables. Except they have a namespace.

class Point:
    x = 1
    y = 2

    @classmethod
    def move(cls, x, y):
        cls.x += x
        cls.y += y

def main():
    print(Point.x)

Class variables are assign soon as they are read. You can print (Point.x) after Point class. You can only have one copy of a class container. If you want more then one. Use a class object.

What is @classmethod. @ is just a decorator follow by a name. @classmethod is a built in decorator. All @classmethod does is pass the class to the method. Instead of refering to class name. You just use cls. cls.x += x which is Point.x += x.

Class Object

What are class object. It an object orient container that you can create many times. It use to make your own custom type.

class Point:
    def __init__(self, x, y)
        self.x = x
        self.y = y

    def move(self, x, y):
        self.x += x
        self.y += y

def main():
    a = Point(1, 1)

The __init__ method creates and initializes object container. You see self. Self is not a keyword. Just a standard variable that get assign a python class object. Any methods you make for class object. Must also have self as first argument. All methods are part of the class namespace. They not part of class object. Just in scope of class object.

Using Class Object And Class Variable

class Person:
    idn = 1000

    def __init__(self, name):
        self.name = name
        self.idn = Person.idn
        Person.idn += 1

def main():
    database = []
    database.append(Person('Kevin'))
    database.append(Person('Bobbie'))
    database.append(Person('Alex'))

    print(Person.idn)
    for person in database:
        print (person.idn, person.name)

main()

Here it show Person.idn is only created once and not part of class objects. If object did not have idn. Then self.idn would call class variable because it in scope. But soon as you assign self.idn = 1. Then it part of the object. Scope rules. Grab from object first. If not there then grab it from class namespace. If not in class namespace then throw error.