• No results found

Objects and classes. Objects and classes. Jarkko Toivonen (CS Department) Programming in Python 1

N/A
N/A
Protected

Academic year: 2021

Share "Objects and classes. Objects and classes. Jarkko Toivonen (CS Department) Programming in Python 1"

Copied!
17
0
0

Loading.... (view fulltext now)

Full text

(1)
(2)

Programming paradigms of Python

I Python is an object-oriented programminglanguage like Java and C++

I But unlike Java, Python doesn’t force you to use classes, inheritance and methods

I If you like, you can also choose the structural programming paradigm with functions and modules

(3)

Objects in Python

I Every value in Python is an object

I Objects are a way to combine data and the functions that handle that data

I This combination is calledencapsulation

I The data items and functions of objects are calledattributes, and in particular the function attributes are called methods

I For example, the operator + on integers calls a method of integers, and the operator + on strings calls a method of strings

(4)

First class objects

I Functions, modules, methods, classes, etc are all first class objects

I This means that these objects can be

I stored in a container

I passed to a function as a parameter

I returned by a function

I used as a key to a dictionary

(5)

Referring to attributes

I One can access an attribute of an object using the dot operator: object.attribute

I For example: ifLis a list, we can refer to the method append

with L.append. Themethod call can look, for instance, like this: L.append(4)

I Because also modules are objects in Python, we can interpret the expression math.pias accessing the data attributepi of module objectmath

(6)

Types and instances

I Numbers like 2 and 100 are instances of type int. Similarly,

"hello" is an instance of typestr.

I When we write s=set(), we are actually creating a new instance of typeset, and bind the resulting instance object to

(7)

Classes and instance objects

I A user can define his own data types

I These are called classes

I A user can call these classes like they were functions, and they return a new instance objectof that type

(8)

Class definition 1

I An example ofclass definition

class MyClass(object):

"""Documentation string of the class""" def __init__(self, param1, param2):

"This initialises an instance of type ClassName" self.b = param1 # creates an instance attribute c = param2 # creates a local variable # statements ...

def f(self, param1):

"""This is a method of the class""" # some statements

(9)

Class definition 2

I The class definition starts with theclass statement

I With this statement you give a name for your new type, and also in parentheses list thebase classes of your class

I The next indented block is theclass body

I After the whole class body is read, a new type is created

I Note that no instances are created yet

I All the attributes and methods of the class are defined in the class body

(10)

Class definition 3

I The example class has two methods: init andf

I Note that their first parameter is special: self. It corresponds tothis variable of C++ or Java

I init does the initialisation when an instance is created

I At instantiation with i=MyClass(2,3) the parameters

param1andparam2are bound to values 2 and 3, respectively

I Now that we have an instancei, we can call its method f

with the dot operator: i.f(1)

I The parameters offare bound in the following way:

(11)

Class definition 4

I There are differences in how an assignment inside a class creates variables

I The attributeais at class level and is common for all instances of the class MyClass

I The variable cis a local variable of the function init , and cannot therefore be used outside the function

I The attributebis specific to each instance ofMyClass. Note that self refers to the current instance

I An example: for objects x=MyClass(1,0) and

(12)

Methods

I All methods of a class have a mandatory first parameter which refers to the instance on which you called the method

I This parameter is usually namedself

I If you want to access the class attribute afrom a method of the class, use the fully qualified form MyClass.a

I The methods whose names both begin and end with two underscores are called special methods. For example, init

is a special method. These methods will be discussed in detail later

(13)

Class attributes

I If a name in Python begins with an underscore, it means that the name is meant to be private. For instance, the name

hiddenis a private name

I This means you should not try to access that name. It is just some implementation specific name, not part of the public interface

I This is meant to be a hint for a user. Python itself doesn’t enforce this rule

I The attributes doc and bases exists for every class, and contain the docstring of the class and the tuple of base

(14)

Instances 1

I We can create instances by calling a class like it were a function: i = ClassName(...)

I Then parameters given in the call will be passed to the

init function

I In the init method you can create the instance specific attributes

I If init is missing, we can create an instance without giving any parameters. As a consequence, the instance has no attributes

I Later you can (re)bind attributes with the assignment

(15)

Instances 2

I If that attribute did not exist before, it will be added to the instance with the assigned value

I In Python we really can add or delete attributes to/from an existing instance

I This is possible because the attribute names and the corresponding values are actually stored in a dictionary

I This dictionary is also an attribute of the instance and is called dict

I Another standard attribute in addition to dict is called

(16)

Attribute lookup (simplified version) 1

I Suppose x is an instance of class X, and we want to read an attribute x.a

I The lookup has three phases:

I First it is checked whether the attribute a is an attribute of the instance x

I If not, then it is checked whether a is a class attribute of x’s class X

(17)

Attribute lookup (simplified version) 2

I If instead we want to bind the attribute a, things are much simpler

I x.a = valuewill set the instance attribute

I And X.a = valuewill set the class attribute

I Note that if a base of X, the class X, and the instance x each have an attribute calleda, then x.ahides X.a, and X.ahides the attribute of the base class

References

Related documents