Classes and Objects

Dr Andy Evans

[Fullscreen]

Review

  • Object Oriented Programming centres on objects: variables that include other variables and functions.
  • Each object has a particular area of work.
  • Often these objects are written by other people and we use them. Code reuse is easy.
  • We can access the inside of objects using the dot operator "."

Object Oriented Programming

  • Scripting languages are very high level - you don't need to know how code works to use it.
  • Because of this, OOP is rarer with beginners than in systems/application languages.
  • Nevertheless, OOP:
    1. Produces cleaner code that's easier to maintain.
    2. Helps to understand how code works, and therefore the solution to issues.
    3. Will be needed if you decide to build anything complicated or with user interactions.

Classes

  • The core structure in OOP is the class.
  • Classes are templates for making objects. You make objects ("instantiate" a class; make an instance of a class), like this:
    object_name = ClassName()
  • Classes are text outlining code much like any other.
  • In Python you can have multiple classes embedded throughout programs, but it is good practice to organise classes in modules.
  • Modules are text files of code, often classes, that work in a particular themed area. Unlike libraries in other languages, it is not unusually to have multiple classes in a single text file. Thought therefore needs to be given to reusability as modules are designed.

Form of a module/class

# Main program

import agentframework
agent_1 = agentframework.Agent()
  • The name of the module is determined by the filename. It is short, lowercase, and all one word. The name of the class starts with a capital and is in CamelCase. The name of the object is lowercase with underscores.
  • pass is a keyword that allows you to create empty blocks and clauses that do nothing but compile.
  • To work, the module file should be in the same directory (or somewhere Python knows about).
# agentframework.py

class Agent():
    pass

Import

  • This is a very explicit style:
    import agentframework
    agent_1 = agentframework.Agent()

    There is little ambiguity about which Agent we are after (if other imported modules have Agent classes).
  • This is safest as you have to be explicit about the module. Provided there aren't two modules with the same name and class, you are fine.
  • If you're sure there's no other Agent, you can:
    from agentframework import Agent
    agent_1 = Agent()
    This just imports this one class.

Objects' properties

  • You can tell the class of objects using:
    print(type(agent_1)) #
  • To check the class:
    print(isinstance(agent_1, agentframework.Agent)) # True
  • Instead of a single class for isinstance, you can also use a tuple of classes and it will return true if any match.

What's happening?

  • When you make an object, the parentheses suggest a function is being called.
  • That function is called a constructor. It is invisible if not explicitly written.
  • If we want to (and we usually do), we can override the invisible default version by writing our own.
  • Overriding is where you write over invisible code with your own in a class. We'll see where invisible code comes from when we look at inheritance.

__init__

  • Here's the basic form of a class with a constructor:
    class Agent():
        def __init__ (self):
            pass
  • The name __init__ is special and ideally reserved for this purpose. The underscores are there to make the name so unusual that we're unlikely to mess with it.

Self

  • You'll see that the constructor is a function that takes in one variable, "self".
  • But equally, we don't send any arguments in:
    agent_1 = agentframework.Agent()
  • So what gives?

Self

  • We can make functions inside classes, and then call them from objects:
    class Agent() :
        def hi(self):
            print("hello world")
    --------------------------------
    agent_1 = agentframework.Agent()
    agent_1.hi()

Methods

  • When they are used, functions in classes and objects are sent to the calling code wrapped in a whole bunch of stuff. To indicate this, Python calls them methods. (Note that in some languages methods are synonymous with functions and procedures, while in some methods and functions have different calls and actions).
  • One thing that happens between call and action is that a variable representing the object is injected into the call. By tradition this is called "self" (it's not a keyword). All methods therefore take in at least one variable (usually called self)
    agent_1 = agentframework.Agent()
    def __init__ (self):
  • self is the object the function lives inside; in this case agent_1.
  • In general, there's two ways of calling functions: They may be bound to objects:
    a = "hello world"
    a.upper()
  • Or unbound and called from the class:
    str.upper(a)
  • In actual fact, in most cases, if you call the former, what happens is that the latter runs, i.e. the method in the class, not the object. This means that for methods that apparently take nothing in, there actually has to be a variable label (self) waiting to assign to the object passed in.
  • This actually helps quite a lot when trying to understand the documentation - for example, how sorting functions (which don't seem to take in the sorted thing) work.

Self

  • self therefore represents the object.
  • Although the self object you get passed is immutable in itself, the contents can be changed.
  • Therefore, if we want to make variables and store data inside an object, we store it inside self.

Instance variables

# Main program

import agentframework
agent_1 = agentframework.Agent()
agent_1.y = 100
agent_1.x = 50
print(agent_1.y)
  • So, here's a classic class.
  • Objects can contain other objects as variables.
  • We can access these from the object using the dot operator.
  • We define the variables within the self object, and within init (we'll come to why, shortly).
# agentframework.py

class Agent():
    def __init__ (self):
        self.y = None
        self.x = None
# Main program

import agentframework
agent_1 = agentframework.Agent()
agent_1.lat = 100
agent_1.x = 50
print(agent_1.y)
  • Be warned, however, that because Python is a dynamic language, it is quite possible to alter objects by inventing variables on the fly.
  • And you have to watch out for spelling mistakes:
    agent_1.yy = 100
    print(agent_1.y)
# agentframework.py

class Agent():
    def __init__ (self):
        self.y = None
        self.x = None

__init__

  • There's nothing to stop you adjusting the init to take in other data:
    class Agent():
        def __init__ (self, y, x):
            self.y = y
            self.x = x

    pt1 = agentframework.Agent(100,50)

Objects

  • We can make multiple different objects from the same class template - like taking a photocopy.
    agent_1 = agentframework.Agent()
    agent_2 = agentframework.Agent()
  • These are not the same objects:
    agent_1.y = 48
    agent_2.y = 44
    print(agent_1.y) # 48

Comparing two objects

  • Take the following examples:
    a = A()
    b = A() # Same content as 'a' but different object.
    c = a # Same object, two labels.
  • These are the comparisons:
    a is c # True - same object.
    a is b # False
    a == b # True - same content, different objects.
    # But only true where supported, e.g. numbers and strings.

Functions

# Main program
import agentframework
agent_1 = agentframework.Agent()
agent_1.randomize()
print(agent_1.y, agent_1.x)
  • We can also build and use other methods for objects.
# agentframework.py
import random
class Agent():
    def __init__(self):
        self.y = None
        self.x = None
    def randomize(self):
        self.y = random.randint(0,99)
        self.x = random.randint(0,99)

Variable scope review

  • We've seen objects can contain variables (other objects) that we can access with the dot operator:
    object_name.variable_name
  • However, when we set them up, the scoping issues become important.
  • Scope, remember, means variables can only be seen in the block in which they are assigned.
  • Previously we saw we could use the global keyword inside functions to indicate we wanted a variable outside the function.

Variables

  • Classes are complicated because there are several things going on:
    the module;
    the class;
    the object;
    methods within the class/~object.
    This makes things complicated: for example, what scale does "global" in a method refer to?
  • Depending where we set them up, variables can be:
    global within the module;
    class attributes;
    object instance variables;
    method local variables.
    It is very easy to get the four confused.
  • Broadly speaking you can see most things in most places, but you need to refer to them properly. The only thing you can't access other than where it is made is method local variables.
# module start
global_variable = None
class ClassA():
    class_attribute = None
    def __init__(self):



        self.instance_variable = None
        method_local_variable = None

    def another_method(self):
# module start
print(global_variable)
class ClassA():
    print(class_attribute)
    def __init__(self):
        global global_variable
        print(global_variable)
        print(ClassA.class_attribute)
        print(self.instance_variable)
        print(method_local_variable)

    def another_method(self):
        # No access to method_local_variable here.

Global variables and class attributes

  • In general, both global and class-level variables are dangerous. Changing them in one place changes them everywhere.
  • You may rely on a variable being one value, while another part of the system may be altering it.
  • We call such issues side-effects: unintended processing changes caused by variable value changes (though some programmers think of even assignments as side effects as they change the values variable labels refer to!).
  • We try to minimise possible side-effects by keeping scope as small as possible.

Instance variables vs class attributes

  • Say we do this:
    agent_1 = agentframework.Agent()
    print(agent_1.variable)
  • If an instance variable exists with this name, we get this.
  • If not, and a class attribute exists, we get this.
  • We can also get the latter with:
    print(agentframework.Agent.variable)
  • But if we assign the variable (in totality, not mutably) we get a new instance variable.