python class

基本语法//属性与封装//方法//继承和组合//多态//特殊方法//wxpython

当时想用static变量想到类的..

基本语法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class class_name(base_class):
class_var
def methods(self, args):
do something

#!/usr/bin/python
# -*- coding: utf-8 -*-
class A:
#classic class 没有父类
"""this is class A"""
pass
__slots__=('x','y') # 可访问"槽"内外的属性
def test(self):
# classic class test
"""this is A.test()"""
print "A class"

class B(object):
#new class 有父类,python3 都是这种,引入了super的概念
"""this is class B"""
__slots__=('x','y') # 只能访问"槽"里面的属性
pass
def test(self):
# new class test
"""this is B.test()"""
print "B class"


if __name__ == '__main__':
a=A()
b=B()

python是动态语言..可以直接任意的添加属性(槽..封死去路)

构造函数__init__

1
2
3
4
5
6
7
8
class Car(object):
country = u'中国'
def __init__(self, length, width, height, owner=None):
self.owner = owner
self.length = length
self.width = width
self.height = height
self.country = "china"

属性

共有

1
2
3
# 公有属性
del a.country
a.__class__.country

私有属性

  1. 加两个下划线 不能直接访问到

    _className__property

  2. 只加一个下划线 从自己约束不直接访问

  3. 前后都加两个下划线 系统自带属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#copyRight by heibanke

class Car(object):
country = u'中国'
def __init__(self, length, width, height, owner=None):
self.__owner = owner

assert length>0,"length must larger than 0"
self._length = length
self._width = width
self._height = height

def getOwner(self):
return self.__owner
def setOwner(self, value):
self.__owner = value

def getLength(self):
return self._length

def setLength(self,value):
assert value>0,"length must larger than 0"
self._length = value

@描述符

加上@property变成有getter的对象

然后就可以像用属性 使用 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#copyRight by heibanke

class Car(object):
country = u'中国'
def __init__(self, length, width, height, owner=None):
self._owner = owner
self._length = length
self._width = width
self._height = height

@property
def owner(self):
return self._owner
@owner.setter
def owner(self, value):
self._owner = value
@owner.deleter
def owner(self):
self._owner = None

@property
def length(self):
return self._length
@length.setter
def length(self, value):
assert value>0,"length must larger than 0"
self._length = value

if __name__ == '__main__':
a = Car(1.2,1.4,1.5,u'黑板客')
print a.owner
del a.owner
print a.owner
a.length=-1

..attr继续优化…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#copyRight by heibanke

class Car(object):
country = u'中国'
__slots__=('length','width','height','owner','__dict__')

def __init__(self, length, width, height, owner=None):
self.owner = owner
self.length = length
self.width = width
self.height = height

def __getattr__(self,name): # 没找到的时候调用
print "__getattr__",name
return self.__dict__.get(name,None)

def __setattr__(self,name,value):
print "__setattr__",name
if name!='owner':
assert value>0, name+" must larger than 0"
self.__dict__[name]=value

def __delattr__(self,name):
print "__delattr__",name
if name=='owner':
self.__dict__[name]=None


if __name__ == '__main__':
a = Car(1.2,1.4,1.5,u'黑板客')
"""
print a.owner
del a.owner
print a.owner
a.length=1

print a.country
a.country = 'china'
print a.country
"""

a.name = u"一汽"

…attr与slots搭配使用时会产生的问题

没有 slots 没有对 dict 进行隐藏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#copyRight by heibanke

class Car(object):
country = u'中国'
__slots__=('length','width','height','owner','__dict__')

def __init__(self, length, width, height, owner=None):
self.owner = owner
self.length = length
self.width = width
self.height = height

def __getattr__(self,name):
print "__getattr__",name
assert name in self.__slots__, "Not have this attribute "+name
return self.__dict__.get(name,None)

def __setattr__(self,name,value):
print "__setattr__",name
assert name in self.__slots__, "Not have this attribute "+name

if name!='owner':
assert value>0, name+" must larger than 0"
self.__dict__[name]=value

def __delattr__(self,name):
print "__delattr__",name
assert name in self.__slots__, "Not have this attribute "+name
if name=='owner':
self.__dict__[name]=None

if __name__ == '__main__':
a = Car(1.2,1.4,1.5,u'黑板客')
"""
print a.owner
del a.owner
print a.owner
a.length=1

print a.country
a.country = 'china'
print a.country

a.name = u"一汽"
"""

方法

类方法, 实例方法@classmethod, 静态方法@staticmethod, 特殊方法

  • 形式区别

通过类和实例进行,不能直接调用

有自己的特殊参数 self, cls

1
2
3
4
5
> @classmethod
> def from_string(cls,date_as_string):
> return cls(map(int,date_as_string.split('-')))
>
>

>

有自己的声明语法

  • 实质区别

绑定类

绑定实例对象

无绑定

特殊方法

属性访问

1
2
3
__getattr__
__setattr__
__getattribute__

实例生成

1
2
__init__
__new__

数字计算

1
2
3
4
5
6
__add__ # 运算符重载
__sub__
__mul__
__div__
__pow__
__round__

调用方法

1
2
3
4
__str__ # print
__repr__ # 在解释器中敲出这个类之后的显示(一般给计算机看的东西)
__len__
__bool__ # if

比较大小

1
2
3
4
5
6
7
8
9
__cmp__
'''
l : less
t : than
e : equal
g : great
n : negative
'''

__lt__ __le__ __eq__ __ne__ __gt__ __ge__

集合访问

1
2
3
__setslice__ __getsclice__ # 集合切片
__getitem__ __setitem__ # 字典遍历
__contains__ # if a in b

迭代器

1
2
__iter__
__next__

继承

多重继承:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class A:
a = 1
b = 1

class B(A):
a = 2

class C(A):
a = 3
b = 3
c = 3

class D(B,C):
pass

import inspect
inspect.getmro(D) # Method Resolution Order
# Classic Dfs
# New Bfs

钻石继承

1
2
super(D,self).method()
多重继承之后只执行一遍...

组合

has a

is a

1
2
3
4
5
6
class De(object):
def __init__(self, *args):
self.members = list(args)

def addMember(self, person):
self.members.append(person)
文章目录
  1. 1. 基本语法
    1. 1.1. 构造函数__init__
  2. 2. 属性
    1. 2.0.1. 共有
    2. 2.0.2. 私有属性
    3. 2.0.3. @描述符
    4. 2.0.4. ..attr继续优化…
    5. 2.0.5. …attr与slots搭配使用时会产生的问题
  • 3. 方法
    1. 3.1. 特殊方法
      1. 3.1.1. 属性访问
      2. 3.1.2. 实例生成
      3. 3.1.3. 数字计算
      4. 3.1.4. 调用方法
      5. 3.1.5. 比较大小
      6. 3.1.6. 集合访问
      7. 3.1.7. 迭代器
  • 4. 继承
    1. 4.1. 多重继承:
    2. 4.2. 钻石继承
  • 5. 组合