Classesx

wakecabbagepatchΛογισμικό & κατασκευή λογ/κού

18 Νοε 2013 (πριν από 3 χρόνια και 10 μήνες)

71 εμφανίσεις

CLASSES

Python Workshop

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

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

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



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

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
!!!"

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


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!!

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

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



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)


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