1 / 8

Lecture 26

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.

reece
Download Presentation

Lecture 26

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 26 Introduction to Classes

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

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

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

  5. The MultiSided Die • The Data members • The number of sides • The current value • The Methods • getValue() • setValue() • roll() • __int__( ) • __str__( )

  6. 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)

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

  8. 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]

More Related