【Python】Object Oriented Programming

以实现 x-y 坐标为例,定义一个类:

 1 class Coordinate(object):
 2     def __init__(self, x, y):
 3         self.x = x
 4         self.y = y
 5     def distance(self, other):
 6         x_diff_sq = (self.x - other.x)**2
 7         y_diff_sq = (self.y - other.y)**2
 8         return (x_diff_sq + y_diff_sq)**0.5
 9     def __str__(self):
10         return "<" + str(self.x) + "," + str(self.y) + ">"

class Coordinate(object):  中,object 为其继承的父类

__init__ :构造函数,定义类中的属性;参数self代表对象本身,例如 c = Coordinate(3, 4) ,c 作为 self 参数被输入构造函数中

__str__ :print self

 

【其他 special operators】https://docs.python.org/3/reference/datamodel.html#basic-customization

例如, __add__ 加号 +、 __sub__ 减号 −、 __eq__ 等于 ==、 __lt__ 小于 <、 __len__ 长度 len(·) 等

 

【定义 Getters 和 Setters】

 1 class Animal(object):
 2     def __init__(self, age):
 3         self.age = age
 4         self.name = None
 5     
 6     #getter
 7     def get_age(self):
 8         return self.age
 9     def get_name(self):
10         return self.name
11 
12     #setter
13     def set_age(self, newage):
14         self.age = newage
15     def set_name(self, newname="")
16         self.name = newname

访问数据属性的时候,应当从类的外部调用 Getters 和 setters,用 a.get_age() 比 a.age 安全性更好。

 

【Default Arguments】

1 def set_name(self, newname = ""):
2     self.name = newname
1 a.set_name()
2 print(a.get_name()) # prints ""
3 
4 a.set_name("Harman")
5 print(a.get_name()) # prints "Harman"

 

【Class Variables 和 Instance Variables】

1 class Rabbit(Animal):
2     tag = 1
3     def __init__(self, age, parent1=None, parent2=None):
4         Animal.__init(self, age)
5         self.parent1 = parent1
6         self.parent2 = parent2
7         self.rid = Rabbit.tag
8         Rabbit.tag += 1

该例中, tag 为 class variable,其变量值由该类的所有实例共享; self.rid 为 instance variable,是每个实例独有的。

posted @ 2021-09-12 15:13  harman-chen  阅读(37)  评论(0编辑  收藏  举报