Week 6a - Classes
Object-oriented Programming - 1
Capitalize the Class Name
Create a Class
class_obj = ClassName(...)
Parameter self
self
as a parameter of the method of class, which on behalf of class itself
double underbar
- These method get called behind your back by Python
- special function
__init__
__str__
(print Class
can automatically call this method, also we can call it byprint str(Class)
)
- don’t use it for normal function
Object-oriented Programming - 2
suitable for other situation
1 Class ball -> different Class Domain (RectangularDomain or CircleDomain)
Working with Objects
We can write a function draw()
in Class, don’t forget to pass parameter canvas
to this function
Week 6b - Tiled Image
Programming Tips - 6
Object Returned by __init__
__init__
will return self automatically
Object of Class Share Data like List
##################
# Object shared state
# Mutation of shared state
class Point2:
def __init__(self, coordinates):
self.coords = coordinates
def set_coord(self, index, value):
self.coords[index] = value
def get_coord(self, index):
return self.coords[index]
coordinates = [4, 5]
p = Point2(coordinates)
q = Point2(coordinates)
r = Point2([4, 5])
p.set_coord(0, 10)
print p.get_coord(0)
print q.get_coord(0)
print r.get_coord(0)
##################
# Objects not sharing state
class Point3:
def __init__(self, coordinates):
self.coords = list(coordinates)
def set_coord(self, index, value):
self.coords[index] = value
def get_coord(self, index):
return self.coords[index]
coordinates = [4, 5]
p = Point3(coordinates)
q = Point3(coordinates)
r = Point3([4, 5])
p.set_coord(0, 10)
print p.get_coord(0)
print q.get_coord(0)
print r.get_coord(0)