80 likes | 200 Views
Lecture 26. Introduction to Classes. What is a class?. A class is like a type or a template. In the past we have talked about strings, lists, Rectangles, Circles , etc. All of these are examples of a class.
E N D
Lecture 26 Introduction to Classes
What is a class? • A class is like a type or a template. In the past we have talked about strings, lists, Rectangles, Circles, etc. All of these are examples of a class. • An object is an instance of a class. So a particular Circle with center Point(0,0) and radius 2 which I have named c1 as in • c1 = Circle(Point(0,0), 2) is an example of an object.
The Constructor • Every class has a constructor When I execute c1 = Circle(Point(0,0), 2) I am really calling a constructor to create and initialize the Circle object. A class will generally have some data members as well as some methods to perform operations on that data. Methods are used for other purposes as well.
Methods • The Circle object, c1, has lots of methods such as • draw(<win>) • setFill(<color>) I call the method by writing c1.setFill(“green”) • Generally methods fall into three categories: • Mutators that change the data • Accessors the return the data • Constructor create the object
The MultiSided Die • The Data members • The number of sides • The current value • The Methods • getValue() • setValue() • roll() • __int__( ) • __str__( )
Import random class MSDie: def __init__(self, sides): self.sides = sides self.value = 1 def roll(self): self.value = random.randint(1, self.sides) def getValue(self): return self.value def setValue(self, value): self.value = value def __str__(self): ans = “number on die:” + str(self.value)
The Tuple • A tuple looks like a list but it is enclosed in parentheses. • A tuple is just one more kind of sequence in Python • The others are list and string • A tuple is immutable which means it cannot be changed.
Example • myList = [(1,1), (2, 4), (3,9), (4,16)] • for (x,y) in myList: print x, “ , “, y for item in myList: print item[0], “,”, item[1]