【Python】Object Oriented Programming

以xy坐标为例,定义一个类:

 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

 

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

E.g.,  __add__ +,  __sub__ -,  __eq__ ==,  __lt__ <,  __len__ len(), ...

 

【Getters and 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 and setters should be used outside of class to access data attributes. Better use  a.get_age()  instead of  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 and 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,是每个实例独有的。

【Python】Object Oriented Programming

上一篇:Linux 第三次练习(文本处理工具练习)


下一篇:JVM垃圾回收