目录
3. clean up hierarchy
OOP:
1. to bundle together objects that share some common properties(common attributes, procedures that operate on those attributes)
2. abstraction : 不需要知道实现的细节
1. 调用类方法的两种途径
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
x_diff_sq = (self.x-other.x)**2
y_diff_sq = (self.y-other.y)**2
return (x_diff_sq + y_diff_sq)**0.5
-
1)通过instance调用
c = Coordinate(3, 4)
origin = Coordinate(0, 0)
print(c.distance(origin))
c -> object on which to call method
distance(origin) -> method, parameters not including self, self is implied to be c
2)直接通过类调用方法:
c = Coordinate(3, 4)
origin = Coordinate(0, 0)
print(Coordinate,distance(c, origin))
Coordinate -> name of class
distance(c, origin) -> method,
parameters including an object on which to call the method, representing self
2. setters, getters
- do not directly manipulate the internal representation of an object
- to separate the use of the object from what's inside of it
- anytime to access something inside an object, use the method that gets that part of the object out
3.类属性
class Animal:
id = 1 # 类属性
def __init__(self):
self.id = Animal.id
Animal.id += 1
def get_id(self):
print(self.id)
animal1 = Animal()
animal2 = Animal()
animal1.get_id()
animal2.get_id()
print(animal1.id)
print(animal2.id)
3. clean up hierarchy
before cleanup:
after cleanup:
4. return a copy of the list
5. data hiding
isolate the internal representation from the user: