# 类 --- [TOC] --- ## 创建类 class Person(object): >若类没有继承,则object ## 所有实例化方法传入self def read(self): return r'["Tim", "Bob", "Alice"]' ## 类的声明 demo ``` class Person(object): 'this is a document' __count = 0 @classmethod def how_many(cls): return cls.__count #return Person.__count #效果同上 def __init__(self, name): self.name = name Person.count = Person.count + 1 ``` ### 类的属性的声明 >1. `__count`属性的声明 ,可以在实例之间调用, >3. 调用类的方法可通过 类方法的`cls`调用,可以类名字调用`Person.__count` ### 类的方法的声明 >1. 在方法前加`@classmethod` 类放法中传入类的参数`cls`,可自定义 >2. self 为类的实例的参数 ### 私有化 >1. `_count` 为类的*protected*型 允许本身和子类调用,代码规范,可通过外部访问 >2. `__count` 为类的*private*型只有本身调用 ,代码规范,其实可访问,如 >``` >a = Person() >a._Person__count #需在属性前加类名 >``` ## 继承 ```python class Children(Person): def __init__(self, name, age): super(Children, self).__init__(name) #继承父类的name self.age=age #调用父类的方法 def add(self,number): number+=number result = super(Children,self).add(number) return result ``` > 1. `super(Children, self).method()`将返回当前类继承的父类 ## 重载 ### 基础重载方法 |方法|说明|调用方法| |---|---|---| |__init__|构造函数|`a=Person()`| |__del__|析构方法|`del object` | |__repr__||`repr(obj)`| |__call__(self, value)|函数形式调用|`object("hello")`| |__str__|字符串调用|`str(obj)`,`print(obj)`| |__getitem__(self,index) | 索引取值 |`a[12]`| |__setitem__(self,k,v) | 索引赋值 |`a[12]='asd'`| |__getattr__(self,name) | 访问不存在的属性 |`a.x`| |__setattr__(self,name,value) |设置不存在的属性 |`a.x='hello`| |__iter__(self)/__next__(self) |迭代调用 || >1.` __repr__`与`__str__` 后者倾向于把类当作字符串打印,一般会定义`__repr__ = __str__` ### 比较运算符号 |方法|说明|调用方法| |---|---|---| |__cmp__(self,other) |对象比较 |`cmp(obj, x)`| |__eq__(self,other) |相等判断 |s==s| |__lt__(self,other) |小于判定 |s<3| |__gt__(self,other) |于判定 |s>3| `__iter__`/与`__next__`的配合 ``` class Next(object): def __init__(self, data=1): self.data = data def __iter__(self): return self def __next__(self): if self.data<5: self.data +=1 return self.data else: raise StopIteration for i in Next(3): print(i) ``` `__cmp__`方法实现 ``` class Student(object): def __init__(self, name, score): self.name = name self.score = score def __cmp__(self, s): if self.score >s.score: return -1 elif self.score<s.score: return 1 else: if self.name > s.name: return 1 elif self.name<s.name: return -1 else:  return 0 #实现 L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)] print sorted(L) #[(Alice: 99), (Tim: 99), (Bob: 88) ``` ### 数字运算符 |方法|说明| |---|---| |__add__(self,other) |`object+1`,`other值为1` | |__sub__(self,other) |`object-1` | |__mul__(self,other) |`object*2` | |__div__(self,other) |`object/2` | ### 逻辑符 |方法|说明| |---|---| |__or__(self,other) |`object+1`,`other值为1` | |__and__(self,other) |`object-1` |