本节内容:html
把下面代码用python2 和python3都执行一下python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
#_*_coding:utf-8_*_
class
A:
def
__init__(
self
):
self
.n
=
'A'
class
B(A):
# def __init__(self):
# self.n = 'B'
pass
class
C(A):
def
__init__(
self
):
self
.n
=
'C'
class
D(B,C):
# def __init__(self):
# self.n = 'D'
pass
obj
=
D()
print
(obj.n)
|
classical vs new style:程序员
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import
abc
class
Alert(
object
):
'''报警基类'''
__metaclass__
=
abc.ABCMeta
@abc
.abstractmethod
def
send(
self
):
'''报警消息发送接口'''
pass
class
MailAlert(Alert):
pass
m
=
MailAlert()
m.send()
|
上面的代码仅在py2里有效,python3里怎么实现呢?编程
经过@staticmethod装饰器便可把其装饰的方法变为一个静态方法,什么是静态方法呢?其实不难理解,普通的方法,能够在实例化后直接调用,而且在方法里能够经过self.调用实例变量或类变量,但静态方法是不能够访问实例变量或类变量的,一个不能访问实例变量和类变量的方法,其实至关于跟类自己已经没什么关系了,它与类惟一的关联就是须要经过类名来调用这个方法ide
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class
Dog(
object
):
def
__init__(
self
,name):
self
.name
=
name
@staticmethod
#把eat方法变为静态方法
def
eat(
self
):
print
(
"%s is eating"
%
self
.name)
d
=
Dog(
"ChenRonghua"
)
d.eat()
|
上面的调用会出如下错误,说是eat须要一个self参数,但调用时却没有传递,没错,当eat变成静态方法后,再经过实例调用时就不会自动把实例自己看成一个参数传给self了。函数
1
2
3
4
5
|
Traceback (most recent call last):
File
"/Users/jieli/PycharmProjects/python基础/自动化day7面向对象高级/静态方法.py"
, line
17
,
in
<module>
d.eat()
TypeError: eat() missing
1
required positional argument:
'self'
<
/
module>
|
想让上面的代码能够正常工做有两种办法ui
1. 调用时主动传递实例自己给eat方法,即d.eat(d) 加密
2. 在eat方法中去掉self参数,但这也意味着,在eat中不能经过self.调用实例中的其它变量了spa
1 class Dog(object): 2 3 def __init__(self,name): 4 self.name = name 5 6 @staticmethod 7 def eat(): 8 print(" is eating") 9 10 11 12 d = Dog("ChenRonghua") 13 d.eat()
类方法经过@classmethod装饰器实现,类方法和普通方法的区别是, 类方法只能访问类变量,不能访问实例变量3d
1
2
3
4
5
6
7
8
9
10
11
12
|
class
Dog(
object
):
def
__init__(
self
,name):
self
.name
=
name
@classmethod
def
eat(
self
):
print
(
"%s is eating"
%
self
.name)
d
=
Dog(
"ChenRonghua"
)
d.eat()
|
执行报错以下,说Dog没有name属性,由于name是个实例变量,类方法是不能访问实例变量的
1
2
3
4
5
6
|
Traceback (most recent call last):
File
"/Users/jieli/PycharmProjects/python基础/自动化day7面向对象高级/类方法.py"
, line
16
,
in
<module>
d.eat()
File
"/Users/jieli/PycharmProjects/python基础/自动化day7面向对象高级/类方法.py"
, line
11
,
in
eat
print
(
"%s is eating"
%
self
.name)
AttributeError:
type
object
'Dog'
has no attribute
'name'
|
此时能够定义一个类变量,也叫name,看下执行效果
class
Dog(
object
):
name
=
"我是类变量"
def
__init__(
self
,name):
self
.name
=
name
@classmethod
def
eat(
self
):
print
(
"%s is eating"
%
self
.name)
d
=
Dog(
"ChenRonghua"
)
d.eat()
#执行结果
我是类变量
is
eating
|
属性方法的做用就是经过@property把一个方法变成一个静态属性
class
Dog(
object
):
def
__init__(
self
,name):
self
.name
=
name
@property
def
eat(
self
):
print
(
" %s is eating"
%
self
.name)
d
=
Dog(
"ChenRonghua"
)
d.eat()
|
调用会出如下错误, 说NoneType is not callable, 由于eat此时已经变成一个静态属性了, 不是方法了, 想调用已经不须要加()号了,直接d.eat就能够了
1
2
3
4
5
|
Traceback (most recent call last):
ChenRonghua
is
eating
File
"/Users/jieli/PycharmProjects/python基础/自动化day7面向对象高级/属性方法.py"
, line
16
,
in
<module>
d.eat()
TypeError:
'NoneType'
object
is
not
callable
|
正常调用以下
d
=
Dog(
"ChenRonghua"
)
d.eat
输出
ChenRonghua
is
eating
|
好吧,把一个方法变成静态属性有什么卵用呢?既然想要静态变量,那直接定义成一个静态变量不就得了么?well, 之后你会需到不少场景是不能简单经过 定义 静态属性来实现的, 好比 ,你想知道一个航班当前的状态,是到达了、延迟了、取消了、仍是已经飞走了, 想知道这种状态你必须经历如下几步:
1. 链接航空公司API查询
2. 对查询结果进行解析
3. 返回结果给你的用户
所以这个status属性的值是一系列动做后才获得的结果,因此你每次调用时,其实它都要通过一系列的动做才返回你结果,但这些动做过程不须要用户关心, 用户只须要调用这个属性就能够,明白 了么?
1 class Flight(object): 2 def __init__(self,name): 3 self.flight_name = name 4 5 6 def checking_status(self): 7 print("checking flight %s status " % self.flight_name) 8 return 1 9 10 @property 11 def flight_status(self): 12 status = self.checking_status() 13 if status == 0 : 14 print("flight got canceled...") 15 elif status == 1 : 16 print("flight is arrived...") 17 elif status == 2: 18 print("flight has departured already...") 19 else: 20 print("cannot confirm the flight status...,please check later") 21 22 23 f = Flight("CA980") 24 f.flight_status 25 26 航班查询
cool , 那如今我只能查询航班状态, 既然这个flight_status已是个属性了, 那我可否给它赋值呢?试试吧
1
2
3
|
f
=
Flight(
"CA980"
)
f.flight_status
f.flight_status
=
2
|
输出, 说不能更改这个属性,我擦。。。。,怎么办怎么办。。。
1
2
3
4
5
6
|
checking flight CA980 status
flight
is
arrived...
Traceback (most recent call last):
File
"/Users/jieli/PycharmProjects/python基础/自动化day7面向对象高级/属性方法.py"
, line
58
,
in
<module>
f.flight_status
=
2
AttributeError: can't
set
attribute
|
固然能够改, 不过须要经过@proerty.setter装饰器再装饰一下,此时 你须要写一个新方法, 对这个flight_status进行更改。
1 class Flight(object): 2 def __init__(self,name): 3 self.flight_name = name 4 5 6 def checking_status(self): 7 print("checking flight %s status " % self.flight_name) 8 return 1 9 10 11 @property 12 def flight_status(self): 13 status = self.checking_status() 14 if status == 0 : 15 print("flight got canceled...") 16 elif status == 1 : 17 print("flight is arrived...") 18 elif status == 2: 19 print("flight has departured already...") 20 else: 21 print("cannot confirm the flight status...,please check later") 22 23 @flight_status.setter #修改 24 def flight_status(self,status): 25 status_dic = { 26 : "canceled", 27 :"arrived", 28 : "departured" 29 } 30 print("\033[31;1mHas changed the flight status to \033[0m",status_dic.get(status) ) 31 32 @flight_status.deleter #删除 33 def flight_status(self): 34 print("status got removed...") 35 36 f = Flight("CA980") 37 f.flight_status 38 f.flight_status = 2 #触发@flight_status.setter 39 del f.flight_status #触发@flight_status.deleter
注意以上代码里还写了一个@flight_status.deleter, 是容许能够将这个属性删除
1 class Foo: 2 """ 描述类信息,这是用于看片的神奇 """ 3 4 def func(self): 5 pass 6 7 print Foo.__doc__ 8 #输出:类的描述信息
__module__ 表示当前操做的对象在那个模块
__class__ 表示当前操做的对象的类是什么
1 class C: 2 3 def __init__(self): 4 self.name = 'wupeiqi'
1 from lib.aa import C 2 3 obj = C() 4 print obj.__module__ # 输出 lib.aa,即:输出模块 5 print obj.__class__ # 输出 lib.aa.C,即:输出类
析构方法,当对象在内存中被释放时,自动触发执行。
注:此方法通常无须定义,由于Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,由于此工做都是交给Python解释器来执行,因此,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的
5. __call__ 对象后面加括号,触发执行。
注:构造方法的执行是由建立对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()
1 class Foo: 2 3 def __init__(self): 4 pass 5 6 def __call__(self, *args, **kwargs): 7 8 print '__call__' 9 10 11 obj = Foo() # 执行 __init__ 12 obj() # 执行 __call__
1 class Province: 2 3 country = 'China' 4 5 def __init__(self, name, count): 6 self.name = name 7 self.count = count 8 9 def func(self, *args, **kwargs): 10 print 'func' 11 12 # 获取类的成员,即:静态字段、方法、 13 print Province.__dict__ 14 # 输出:{'country': 'China', '__module__': '__main__', 'func': <function func at 0x10be30f50>, '__init__': <function __init__ at 0x10be30ed8>, '__doc__': None} 15 16 obj1 = Province('HeBei',10000) 17 print obj1.__dict__ 18 # 获取 对象obj1 的成员 19 # 输出:{'count': 10000, 'name': 'HeBei'} 20 21 obj2 = Province('HeNan', 3888) 22 print obj2.__dict__ 23 # 获取 对象obj1 的成员 24 # 输出:{'count': 3888, 'name': 'HeNan'}
1 class Foo: 2 3 def __str__(self): 4 return 'alex li' 5 6 7 obj = Foo() 8 print obj 9 # 输出:alex li
用于索引操做,如字典。以上分别表示获取、设置、删除数据
1 class Foo(object): 2 3 def __getitem__(self, key): 4 print('__getitem__',key) 5 6 def __setitem__(self, key, value): 7 print('__setitem__',key,value) 8 9 def __delitem__(self, key): 10 print('__delitem__',key) 11 12 13 obj = Foo() 14 15 result = obj['k1'] # 自动触发执行 __getitem__ 16 obj['k2'] = 'alex' # 自动触发执行 __setitem__ 17 del obj['k1']
1
2
3
4
5
6
7
8
|
class
Foo(
object
):
def
__init__(
self
,name):
self
.name
=
name
f
=
Foo(
"alex"
)
|
上述代码中,obj 是经过 Foo 类实例化的对象,其实,不只 obj 是一个对象,Foo类自己也是一个对象,由于在Python中一切事物都是对象。
若是按照一切事物都是对象的理论:obj对象是经过执行Foo类的构造方法建立,那么Foo类对象应该也是经过执行某个类的 构造方法 建立。
1
2
|
print
type
(f)
# 输出:<class '__main__.Foo'> 表示,obj 对象由Foo类建立
print
type
(Foo)
# 输出:<type 'type'> 表示,Foo类对象由 type 类建立
|
因此,f对象是Foo类的一个实例,Foo类对象是 type 类的一个实例,即:Foo类对象 是经过type类的构造方法建立。
那么,建立类就能够有两种方式:
a). 普通方式
1
2
3
4
|
class
Foo(
object
):
def
func(
self
):
print
'hello alex'
|
b). 特殊方式
1
2
3
4
5
6
7
|
def
func(
self
):
print
'hello wupeiqi'
Foo
=
type
(
'Foo'
,(
object
,), {
'func'
: func})
#type第一个参数:类名
#type第二个参数:当前类的基类
#type第三个参数:类的成员
|
1 def func(self): 2 print("hello %s"%self.name) 3 4 def __init__(self,name,age): 5 self.name = name 6 self.age = age 7 Foo = type('Foo',(object,),{'func':func,'__init__':__init__}) 8 9 f = Foo("jack",22) 10 f.func() 11 12 加上构造方法
So ,孩子记住,类 是由 type 类实例化产生
那么问题来了,类默认是由 type 类实例化产生,type类中如何实现的建立类?类又是如何建立对象?
答:类中有一个属性 __metaclass__,其用来表示该类由 谁 来实例化建立,因此,咱们能够为 __metaclass__ 设置一个type类的派生类,从而查看 类 建立的过程。
1 #_*_coding:utf-8_*_ 2 3 class MyType(type): 4 def __init__(self, child_cls, bases=None, dict=None): 5 print("--MyType init---", child_cls,bases,dict) 6 #super(MyType, self).__init__(child_cls, bases, dict) 7 8 # def __new__(cls, *args, **kwargs): 9 # print("in mytype new:",cls,args,kwargs) 10 # type.__new__(cls) 11 def __call__(self, *args, **kwargs): 12 print("in mytype call:", self,args,kwargs) 13 obj = self.__new__(self,args,kwargs) 14 15 self.__init__(obj,*args,**kwargs) 16 17 class Foo(object,metaclass=MyType): #in python3 18 #__metaclass__ = MyType #in python2 19 20 def __init__(self, name): 21 self.name = name 22 print("Foo ---init__") 23 24 def __new__(cls, *args, **kwargs): 25 print("Foo --new--") 26 return object.__new__(cls) 27 28 def __call__(self, *args, **kwargs): 29 print("Foo --call--",args,kwargs) 30 # 第一阶段:解释器从上到下执行代码建立Foo类 31 # 第二阶段:经过Foo类建立obj对象 32 obj = Foo("Alex") 33 #print(obj.name) 34 35 自定义元类
类的生成 调用 顺序依次是 __new__ --> __call__ --> __init__
metaclass 详解文章:http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python 得票最高那个答案写的很是好
经过字符串映射或修改程序运行时的状态、属性、方法, 有如下4个方法
1 def getattr(object, name, default=None): # known special case of getattr 2 """ 3 getattr(object, name[, default]) -> value 4 5 Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. 6 When a default argument is given, it is returned when the attribute doesn't 7 exist; without it, an exception is raised in that case. 8 """ 9 pass 10 11 getattr(object, name, default=None)
判断object中有没有一个name字符串对应的方法或属性(hasattr(object,name))
def setattr(x, y, v): # real signature unknown; restored from __doc__ """ Sets the named attribute on the given object to the specified value. setattr(x, 'y', v) is equivalent to ``x.y = v''
1 def delattr(x, y): # real signature unknown; restored from __doc__ 2 """ 3 Deletes the named attribute from the given object. 4 5 delattr(x, 'y') is equivalent to ``del x.y'' 6 """ 7 8 delattr(x, y)
1 class Foo(object): 2 3 def __init__(self): 4 self.name = 'wupeiqi' 5 6 def func(self): 7 return 'func' 8 9 obj = Foo() 10 11 # #### 检查是否含有成员 #### 12 hasattr(obj, 'name') 13 hasattr(obj, 'func') 14 15 # #### 获取成员 #### 16 getattr(obj, 'name') 17 getattr(obj, 'func') 18 19 # #### 设置成员 #### 20 setattr(obj, 'age', 18) 21 setattr(obj, 'show', lambda num: num + 1) 22 23 # #### 删除成员 #### 24 delattr(obj, 'name') 25 delattr(obj, 'func') 26 27 反射代码示例
动态导入模块
import
importlib
__import__
(
'import_lib.metaclass'
)
#这是解释器本身内部用的
#importlib.import_module('import_lib.metaclass') #与上面这句效果同样,官方建议用这个
参考 http://www.cnblogs.com/wupeiqi/articles/5017742.html
参考:http://www.cnblogs.com/wupeiqi/articles/5040823.html
做业:开发一个支持多用户在线的FTP程序
要求: