IIPP Week 6 - Classes and object-oriented programming

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 by print 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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值