Download presentation
Presentation is loading. Please wait.
Published byGeorgia Brown Modified over 9 years ago
1
CLASSES Python Workshop
2
Introduction Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax and semantics. It is a mixture of the class mechanisms found in C++ and Modula-3. Python classes provide all the standard features of Object Oriented Programming
3
Objects and Classes An object is the basic Python building block, the 'lego brick' with which every program is built. All the elements that we've met up until now - integers, strings, lists, functions etc. - they're all objects. A class is simply a user-defined object that lets you keep a bunch of closely related things "together".
4
Object Oriented Programming Inheritance A way to compartmentalize and reuse classes/objects already defined Encapsulation Grouping together of things that logically belong to each other Polymorphism the ability to create a variable, a function, or an object that has more than one form
5
Class foo # Class foo # http://pytut.infogami.com/node11-baseline.html class Foo: def __str__(self): return "I am an instance of Foo!!!" #main program f = Foo() print f
6
Class Components Class class-identifier class Foo: Constructor special function of the class that is called whenever we create a new instance of the class def __str__(self): Return return "I am an instance of Foo!!!"
7
Instantiation and Call Note how we instantiated the class with f = Foo() This we now have a new object f which has characteristics of this class, and we can use f print f
8
Illustration The following illustration is simple to follow. It is based on our understanding of complex numbers that have two components Real part Imaginary part Let’s see how we can work this!!
9
Class Complex class Complex: def __init__(self, realpart, imagpart): self.r = realpart self.i = imagpart x = Complex(3.0, -4.5) print “x real =“, x.r print “x imaginary = “, x.i
10
Explanation As you can see, the definition of the class class Complex: def __init__(self, realpart, imagpart): self.r = realpart self.i = imagpart The instantiation of the object x x = Complex(3.0, -4.5) The use of the object attributes to print the respective parts print “x real =“, x.r print “x imaginary =“, x.i
12
Question Can you see how the constructor is used to determine the parameters passed to the class when an object is instantiated? def __init__(self, realpart, imagpart): x = Complex(3.0, -4.5)
13
Question Can you see how the attributes are used? self.r = realpart self.i = imagpart And from the main program print “x real =“, x.r print “x imaginary =“, x.i
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.