复习面向对象编程
类:
属性
实例变量(每个实例都单独存放在内存里,互相不影响
类变量(存在类的内存里,所有的实例共享这个内存)
私有属性__var
方法
构造方法(初始化)
析构函数(实例销毁释放时会自动执行,执行自己想要的操作。 默认的析构函数是什么都不干,如果自己写析构函数就是重构)
私有方法
对象:实例化一个类之后得到的对象,又称为类的实例
封装:把一些功能的实现细节不对外暴露
继承:代码的重用
单继承
多继承
广度优先
深度优先
2.7 经典类,深度优先。 新式类,广度优先
3.x 均是广度优先
建议都写新式类:
class Teacher(SchoolMember):
def init(self,name,age,sex,salary,course):
super(Teacher,self).init(name,age)
# 旧方法: SchoolMember.init(self,name,age) ,不方便应对多继承,如果又继承了一个父类,就要再写一次,然后根据优先选取继承的。这种旧方法在多继承就是个bug。
self.salary = salary
继承父类后,父类里可能也有init方法, 子类如果不写init,子类在实例化的时候会用父类的init。 为什么子类自己要init呢?因为实例化时 还有些自己的参数,所以是重构父类的构造函数(覆盖)。然后又有super表示是继承。 整个流程就是 先覆盖父类函数,再通过super继承,再添加自己的参数
继承父类的参数应该一致,如果不一致可以通过组合方式,关联另一个类 self.person = Person(self,job)
多态:接口重用,一种接口多种实现
面向对象高级语法部分
经典类vs新式类
静态方法、类方法、属性方法
类的特殊方法
反射
异常处理
Socket开发基础
作业:开发一个支持多用户在线的FTP程序
静态方法
静态方法:只是名义上归类管理,实际上在静态方法里访问不了类或实例中的任何属性。
@staticmethod 实际上跟类没什么关系了,如果变成静态方法,就相当于截断。 它的作用就相当于单纯的函数,但调用也要通过实例去调用。
类方法
@classmethod
类方法:只能访问类变量,不能访问实例变量。
class Dog(object):
name = 333
def __init__(self, name):
self.name = name
@classmethod
def talk(self):
print("%s is talking" % self.name)
d = Dog('果子哥')
d.talk()
结果:333 is talking
属性方法
属性方法:把一个方法变成一个静态属性,调用的时候不能加括号。 主要作用是隐藏实现细节
如果加括号调用会出以下错误, 说NoneType is not callable, 因为eat此时已经变成一个静态属性了, 不是方法了, 想调用已经不需要加()号了,直接d.eat就可以了
class Dog(object):
def __init__(self, name):
self.name = name
@property
def talk(self):
print("%s is talking" % self.name)
d = Dog('果子哥')
d.talk
结果:
果子哥 is talking
如果talk有其他参数,就不好弄了
比如 ,你想知道一个航班当前的状态,是到达了、延迟了、取消了、还是已经飞走了, 想知道这种状态你必须经历以下几步:
-
连接航空公司API查询
-
对查询结果进行解析
-
返回结果给你的用户
因此这个status属性的值是一系列动作后才得到的结果,所以你每次调用时,其实它都要经过一系列的动作才返回你结果,但这些动作过程不需要用户关心, 用户只需要调用这个属性就可以
class Flight(object):
def __init__(self,name):
self.flight_name = name
def checking_status(self):
print("checking flight %s status " % self.flight_name)
return 1 # 伪代码,返回个1 表示arrived
@property
def flight_status(self):
status = self.checking_status() # 相当于调航空公司的API
if status == 0 :
print("flight got canceled...")
elif status == 1 :
print("flight is arrived...")
elif status == 2:
print("flight has departured already...")
else:
print("cannot confirm the flight status...,please check later")
f = Flight("CA980")
f.flight_status #用户只需要调用这个
航班查询
————————————————————————————————————————————————————————————————————————
class Flight(object):
def __init__(self,name):
self.flight_name = name
def checking_status(self):
print("checking flight %s status " % self.flight_name)
return 1 #伪代码,返回个1
@property
def flight_status(self):
status = self.checking_status() # 相当于调航空公司的API
if status == 0 :
print("flight got canceled...")
elif status == 1 :
print("flight is arrived...")
elif status == 2:
print("flight has departured already...")
else:
print("cannot confirm the flight status...,please check later")
@flight_status.setter
def flight_status(self,status):
print("flight %s has changed status to %s" %(self.flight_name,status))
f = Flight("CA980")
f.flight_status #用户只需要调用这个
f.flight_status = 2
类的特殊成员方法
- doc 表示类的描述信息
class Foo:
""" 这是描述类信息 """
def func(self):
pass
print(Foo.__doc__)
#输出:这是描述类信息
- module 和 class
module 表示当前操作的对象在那个模块
class 表示当前操作的对象的类是什么
class C:
def __init__(self):
self.name = 'wupeiqi'
from lib.aa import C
#lib.aa 表示 aa.py在lib文件夹下。
obj = C()
print(obj.__module__) # 输出 lib.aa,即:输出模块
print(obj.__class__) # 输出 lib.aa.C,即:输出类
-
init 构造方法,通过类创建对象时,自动触发执行。
-
del
析构方法,当对象在内存中被释放时,自动触发执行。注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给Python解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的
-
call 对象后面加括号,触发执行。
注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 call 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()
class Foo:
def __init__(self):
pass
def __call__(self, *args, **kwargs):
print('__call__',args,kwargs)
obj = Foo() # 执行 __init__
obj(1,2,3,name=333) # 执行 __call__
结果:__call__ (1, 2, 3) {'name': 333}
- dict 查看类或对象中的所有成员
class Province:
country = 'China'
def __init__(self, name, count):
self.name = name
self.count = count
def func(self, *args, **kwargs):
print 'func'
# 获取类的成员,即:静态字段、方法、
print(Province.__dict__)
# 输出:{'country': 'China', '__module__': '__main__', 'func': <function func at 0x10be30f50>, '__init__': <function __init__ at 0x10be30ed8>, '__doc__': None}
obj1 = Province('HeBei',10000)
print(obj1.__dict__)
# 获取 对象obj2 的成员
# 输出:{'count': 10000, 'name': 'HeBei'}
obj2 = Province('HeNan', 3888)
print obj2.__dict__
# 获取 对象obj1 的成员
# 输出:{'count': 3888, 'name': 'HeNan'}
- str 如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。
class Foo:
def __str__(self):
return 'alex li'
obj = Foo()
print(obj)
# 输出:alex li
- getitem、setitem、delitem
用于索引操作,如字典。以上分别表示获取、设置、删除数据
class Foo(object):
def __getitem__(self, key):
print('__getitem__',key)
def __setitem__(self, key, value):
print('__setitem__',key,value)
def __delitem__(self, key):
print('__delitem__',key)
obj = Foo()
result = obj['k1'] # 自动触发执行 __getitem__
obj['k2'] = 'alex' # 自动触发执行 __setitem__
del obj['k1']
- new \ metaclass
class Foo(object):
def __init__(self,name):
self.name = name
f = Foo("alex")
上述代码中,obj 是通过 Foo 类实例化的对象,其实,不仅 obj 是一个对象,Foo类本身也是一个对象,因为在Python中一切事物都是对象。
如果按照一切事物都是对象的理论:obj对象是通过执行Foo类的构造方法创建,那么Foo类对象应该也是通过执行某个类的 构造方法 创建。
print(type(f)) # 输出:<class '__main__.Foo'> 表示,obj 对象由Foo类创建
print(type(Foo)) # 输出:<type 'type'> 表示,Foo类对象由 type 类创建
所以,f对象是Foo类的一个实例,Foo类对象是 type 类的一个实例,即:Foo类对象 是通过type类的构造方法创建。
那么,创建类就可以有两种方式:
a). 普通方式
class Foo(object):
def func(self):
print('hello alex')
b). 特殊方式
def func(self):
print('hello wupeiqi')
Foo = type('Foo',(object,), {'func': func})
#type第一个参数:类名
#type第二个参数:当前类的基类
#type第三个参数:类的成员
def func(self):
print("hello %s"%self.name)
def __init__(self,name,age):
self.name = name
self.age = age
Foo = type('Foo',(object,),{'func':func,'__init__':__init__})
f = Foo("jack",22)
f.func()
加上构造方法
那么问题来了,类默认是由 type 类实例化产生,type类中如何实现的创建类?类又是如何创建对象?
答:类中有一个属性 metaclass,其用来表示该类由 谁 来实例化创建,所以,我们可以为 metaclass 设置一个type类的派生类,从而查看 类 创建的过程。
class MyType(type):
def __init__(self,*args,**kwargs):
print("Mytype __init__",*args,**kwargs)
def __call__(self, *args, **kwargs):
print("Mytype __call__", *args, **kwargs)
obj = self.__new__(self)
print("obj ",obj,*args, **kwargs)
print(self)
self.__init__(obj,*args, **kwargs)
return obj
def __new__(cls, *args, **kwargs):
print("Mytype __new__",*args,**kwargs)
return type.__new__(cls, *args, **kwargs)
print('here...')
class Foo(object,metaclass=MyType):
def __init__(self,name):
self.name = name
print("Foo __init__")
def __new__(cls, *args, **kwargs):
print("Foo __new__",cls, *args, **kwargs)
return object.__new__(cls)
f = Foo("Alex")
print("f",f)
print("fname",f.name)
自定义元类
类的生成 调用 顺序依次是 new --> init --> call
metaclass 详解文章:http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python 得票最高那个答案写的非常好
反射
通过字符串映射或修改程序运行时的状态、属性、方法, 有以下4个方法
hasattr(obj,name_str),判断一个对象是否有对应的name_str字符串的方法
getattr(obj,name_str),根据字符串去获取obj对象里的对应的方法的内存地址
setattr(obj,‘y’,z) ,相当于 x.y = v
delattr(d,name_str) ,删除name_str字符串
def getattr(object, name, default=None): # known special case of getattr
"""
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
"""
pass
getattr(object, name, default=None)
判断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''
def delattr(x, y): # real signature unknown; restored from __doc__
"""
Deletes the named attribute from the given object.
delattr(x, 'y') is equivalent to ``del x.y''
"""
运用实例
class Dog(object):
def __init__(self,name):
self.name = name
def eat(self):
print("%s is eating..."%self.name)
d = Dog("BB")
choice = input(">>:").strip()
# if choice == 'eat':
# d.eat()
# # 如果有很多个方法就要判断多次
# #### 检查是否含有成员 ####
print(hasattr(d,choice))
# #### 获取成员 ####
print(getattr(d, 'name'))
getattr(d,choice)()
结果为:>>:eat
True
BB
BB is eating...
class Dog(object):
def __init__(self,name):
self.name = name
def eat(self):
print("%s is eating..."%self.name)
d = Dog("BB")
choice = input(">>:").strip()
if hasattr(d,choice):
func = getattr(d,choice)
func()
结果为:BB is eating...
————————————————————————————————————————————————————————————————
动态装配一个方法:
def bulk(self):
print("%s is yelling..." % self.name)
class Dog(object):
def __init__(self, name):
self.name = name
def eat(self):
print("%s is eating..." % self.name)
d = Dog("BB")
choice = input(">>:").strip()
if hasattr(d, choice):
func = getattr(d, choice)
func()
else:
setattr(d, choice, bulk)
d.bulk(d)
v = getattr(d,choice)
print(v)
func = getattr(d,choice)
func(d)
结果:>>:bulk
BB is yelling...
<function bulk at 0x0000014B7DC230D8>
BB is yelling...
运用示例
class Foo(object):
def __init__(self):
self.name = 'wupeiqi'
def func(self):
return 'func'
obj = Foo()
# #### 检查是否含有成员 ####
hasattr(obj, 'name')
hasattr(obj, 'func')
# #### 获取成员 ####
getattr(obj, 'name')
getattr(obj, 'func')
# #### 设置成员 ####
setattr(obj, 'age', 18)
setattr(obj, 'show', lambda num: num + 1)
# #### 删除成员 ####
delattr(obj, 'name')
delattr(obj, 'func')
反射代码示例
异常处理
参考 http://www.cnblogs.com/wupeiqi/articles/5017742.html
作业:开发一个支持多用户在线的FTP程序
要求:
用户加密认证
允许同时多用户登录
每个用户有自己的家目录 ,且只能访问自己的家目录
对用户进行磁盘配额,每个用户的可用空间不同
允许用户在ftp server上随意切换目录
允许用户查看当前目录下文件
允许上传和下载文件,保证文件一致性
文件传输过程中显示进度条
附加功能:支持文件的断点续传