70 likes | 99 Views
Python – May 19. Review What is the difference between: list, tuple, set, dictionary? When is it appropriate to use each? Creating our own data types: classes/objects Reminder: “meeting” program due tomorrow. Paradigms. Note that there are 3 ways to approach programming
E N D
Python – May 19 • Review • What is the difference between: list, tuple, set, dictionary? • When is it appropriate to use each? • Creating our own data types: classes/objects • Reminder: “meeting” program due tomorrow
Paradigms • Note that there are 3 ways to approach programming • Procedural – follow definition of program: list of operations to perform: verb focus • Object oriented – noun focus: define a type with its attributes and operations • Functional – everything is a function call; loops written as recursion
OO • A different way to approach problem solving – think about the nouns first. • Python supports OO design. • We can define attributes & operations that belong to instances of the class. • Everything is public – no information hiding.
Example class Rectangle: length = 4 # Static & default values width = 3 def area(self): return self.length * self.width # ------------------------------------------ r = Rectangle() print r.length print r.area()
Example (2) • More realistic to allow instances to be different! To initialize attributes, use special function called __init__ class Triangle: def __init__(self, side1, side2, side3): self.a = side1 self.b = side2 self.c = side3 def perimeter(self): return self.a + self.b + self.c t = Triangle(3,4,5) print t.perimeter()
Notes • Python not the best language for true OO. • Unfortunately, can’t have more than 1 “constructor” • When you call an instance method, you literally pass it with 1 fewer parameter than in the declaration – leave off the “self”. definition: def giveRaise(self, percent): … call: bob.giveRaise(4)
Careful! class Rectangle: length = 4 width = 3 def __init__(self, L, W): self.length = L self.width = W # --------------------------------- r1 = Rectangle(10, 8) print Rectangle.length # equals 4 print r1.length # equals 10 Moral – if you have some static values you want to share, don’t confuse yourself by using same name as attribute. Now you see why we always use “self”.