设为首页 收藏本站
查看: 790|回复: 0

[经验分享] python_7 面向对象编程进阶

[复制链接]

尚未签到

发表于 2018-8-10 11:21:28 | 显示全部楼层 |阅读模式
  本节内容:

  •   面向对象高级语法部分

    •   经典类vs新式类  
    •   静态方法、类方法、属性方法
    •   类的特殊方法
    •   反射

  •   异常处理
  •   Socket开发基础
  •   作业:开发一个支持多用户在线的FTP程序
面向对象高级语法部分
经典类vs新式类
  把下面代码用python2 和python3都执行一下
#_*_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:

  •   经典类:深度优先
  •   新式类:广度优先
  •   super()用法
抽象接口
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.调用实例变量或类变量,但静态方法是不可以访问实例变量或类变量的,一个不能访问实例变量和类变量的方法,其实相当于跟类本身已经没什么关系了,它与类唯一的关联就是需要通过类名来调用这个方法
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了。
Traceback (most recent call last):  
  File &quot;/Users/jieli/PycharmProjects/python基础/自动化day7面向对象高级/静态方法.py&quot;, line 17, in <module>
  
    d.eat()
  
TypeError: eat() missing 1 required positional argument: 'self'
  想让上面的代码可以正常工作有两种办法
  1. 调用时主动传递实例本身给eat方法,即d.eat(d)
  2. 在eat方法中去掉self参数,但这也意味着,在eat中不能通过self.调用实例中的其它变量了
class Dog(object):  

  
    def __init__(self,name):
  
        self.name = name
  

  
    @staticmethod
  
    def eat():
  
        print(&quot; is eating&quot;)
  

  

  

  
d = Dog(&quot;ChenRonghua&quot;)
  
d.eat()
类方法  
  类方法通过@classmethod装饰器实现,类方法和普通方法的区别是, 类方法只能访问类变量,不能访问实例变量
class Dog(object):  
    def __init__(self,name):
  
        self.name = name
  

  
    @classmethod
  
    def eat(self):
  
        print(&quot;%s is eating&quot; % self.name)
  

  

  

  
d = Dog(&quot;ChenRonghua&quot;)
  
d.eat()
  执行报错如下,说Dog没有name属性,因为name是个实例变量,类方法是不能访问实例变量的
Traceback (most recent call last):  
  File &quot;/Users/jieli/PycharmProjects/python基础/自动化day7面向对象高级/类方法.py&quot;, line 16, in <module>
  
    d.eat()
  
  File &quot;/Users/jieli/PycharmProjects/python基础/自动化day7面向对象高级/类方法.py&quot;, line 11, in eat
  
    print(&quot;%s is eating&quot; % self.name)
  
AttributeError: type object 'Dog' has no attribute 'name'
  此时可以定义一个类变量,也叫name,看下执行效果
class Dog(object):  
    name = &quot;我是类变量&quot;
  
    def __init__(self,name):
  
        self.name = name
  

  
    @classmethod
  
    def eat(self):
  
        print(&quot;%s is eating&quot; % self.name)
  

  

  

  
d = Dog(&quot;ChenRonghua&quot;)
  
d.eat()
  

  

  
#执行结果
  

  
我是类变量 is eating
属性方法  
  属性方法的作用就是通过@property把一个方法变成一个静态属性
class Dog(object):  

  
    def __init__(self,name):
  
        self.name = name
  

  
    @property
  
    def eat(self):
  
        print(&quot; %s is eating&quot; %self.name)
  

  

  
d = Dog(&quot;ChenRonghua&quot;)
  
d.eat()
  调用会出以下错误, 说NoneType is not callable, 因为eat此时已经变成一个静态属性了, 不是方法了, 想调用已经不需要加()号了,直接d.eat就可以了
Traceback (most recent call last): ChenRonghua is eating  File &quot;/Users/jieli/PycharmProjects/python基础/自动化day7面向对象高级/属性方法.py&quot;, line 16, in <module>    d.eat()TypeError: 'NoneType' object is not callable  正常调用如下
d = Dog(&quot;ChenRonghua&quot;)  
d.eat
  

  
输出
  
ChenRonghua is eating
  好吧,把一个方法变成静态属性有什么卵用呢?既然想要静态变量,那直接定义成一个静态变量不就得了么?well, 以后你会需到很多场景是不能简单通过 定义 静态属性来实现的, 比如 ,你想知道一个航班当前的状态,是到达了、延迟了、取消了、还是已经飞走了, 想知道这种状态你必须经历以下几步:
  1. 连接航空公司API查询
  2. 对查询结果进行解析
  3. 返回结果给你的用户
  因此这个status属性的值是一系列动作后才得到的结果,所以你每次调用时,其实它都要经过一系列的动作才返回你结果,但这些动作过程不需要用户关心, 用户只需要调用这个属性就可以,明白 了么?
  航班查询:
class Flight(object):  
    def __init__(self,name):
  
        self.flight_name = name
  

  

  
    def checking_status(self):
  
        print(&quot;checking flight %s status &quot; % self.flight_name)
  
        return  1
  

  
    @property
  
    def flight_status(self):
  
        status = self.checking_status()
  
        if status == 0 :
  
            print(&quot;flight got canceled...&quot;)
  
        elif status == 1 :
  
            print(&quot;flight is arrived...&quot;)
  
        elif status == 2:
  
            print(&quot;flight has departured already...&quot;)
  
        else:
  
            print(&quot;cannot confirm the flight status...,please check later&quot;)
  

  

  
f = Flight(&quot;CA980&quot;)
  
f.flight_status
  

  
航班查询
  cool , 那现在我只能查询航班状态, 既然这个flight_status已经是个属性了, 那我能否给它赋值呢?试试吧
f = Flight(&quot;CA980&quot;)  
f.flight_status
  
f.flight_status =  2
  输出, 说不能更改这个属性,我擦。。。。,怎么办怎么办。。。
checking flight CA980 status  
flight is arrived...
  
Traceback (most recent call last):
  
  File &quot;/Users/jieli/PycharmProjects/python基础/自动化day7面向对象高级/属性方法.py&quot;, line 58, in <module>
  
    f.flight_status =  2
  
AttributeError: can't set attribute
  当然可以改, 不过需要通过@proerty.setter装饰器再装饰一下,此时 你需要写一个新方法, 对这个flight_status进行更改。
class Flight(object):    def __init__(self,name):  
        self.flight_name = name    def checking_status(self):        print(&quot;checking flight %s status &quot; % self.flight_name)        return  1
  

  

  
    @property    def flight_status(self):
  
        status = self.checking_status()        if status == 0 :            print(&quot;flight got canceled...&quot;)        elif status == 1 :            print(&quot;flight is arrived...&quot;)        elif status == 2:            print(&quot;flight has departured already...&quot;)        else:            print(&quot;cannot confirm the flight status...,please check later&quot;)
  

  
    @flight_status.setter #修改
  
    def flight_status(self,status):
  
        status_dic = {
  
            0 : &quot;canceled&quot;,            1 :&quot;arrived&quot;,            2 : &quot;departured&quot;
  
        }        print(&quot;\033[31;1mHas changed the flight status to \033[0m&quot;,status_dic.get(status) )
  

  
    @flight_status.deleter  #删除
  
    def flight_status(self):        print(&quot;status got removed...&quot;)
  

  
f = Flight(&quot;CA980&quot;)
  
f.flight_status
  
f.flight_status =  2 #触发@flight_status.setter del f.flight_status #触发@flight_status.deleter
类的特殊成员方法
1. __doc__  表示类的描述信息
class Foo:  
    &quot;&quot;&quot; 描述类信息,这是用于看片的神奇 &quot;&quot;&quot;
  

  
    def func(self):
  
        pass
  

  
print Foo.__doc__
  
#输出:类的描述信息
2. __module__ 和  __class__
  __module__ 表示当前操作的对象在那个模块
  __class__     表示当前操作的对象的类是什么
class C:    def __init__(self):  
        self.name = 'wupeiqi'
from lib.aa import C  

  
obj = C()print obj.__module__  # 输出 lib.aa,即:输出模块print obj.__class__      # 输出 lib.aa.C,即:输出类
3. __init__ 构造方法,通过类创建对象时,自动触发执行。
4.__del__
  析构方法,当对象在内存中被释放时,自动触发执行。
注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给Python解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的  5. __call__ 对象后面加括号,触发执行。
  注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()
class Foo:  

  
    def __init__(self):
  
        pass
  

  
    def __call__(self, *args, **kwargs):
  

  
        print '__call__'
  

  

  
obj = Foo() # 执行 __init__
  
obj()       # 执行 __call__
6. __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__
  
# 获取 对象obj1 的成员
  
# 输出:{'count': 10000, 'name': 'HeBei'}
  

  
obj2 = Province('HeNan', 3888)
  
print obj2.__dict__
  
# 获取 对象obj1 的成员
  
# 输出:{'count': 3888, 'name': 'HeNan'}
7.__str__ 如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。
class Foo:  

  
    def __str__(self):
  
        return 'alex li'
  

  

  
obj = Foo()
  
print obj
  
# 输出:alex li
8.__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']9. __new__ \ __metaclass__
class Foo(object):  

  

  
    def __init__(self,name):
  
        self.name = name
  

  

  
f = Foo(&quot;alex&quot;)
  上述代码中,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(&quot;hello %s&quot;%self.name)def __init__(self,name,age):  
    self.name = name
  
    self.age = age
  
Foo = type('Foo',(object,),{'func':func,'__init__':__init__})
  

  
f = Foo(&quot;jack&quot;,22)
  
f.func()
  So ,孩子记住,类 是由 type 类实例化产生
  那么问题来了,类默认是由 type 类实例化产生,type类中如何实现的创建类?类又是如何创建对象?
  答:类中有一个属性 __metaclass__,其用来表示该类由 谁 来实例化创建,所以,我们可以为 __metaclass__ 设置一个type类的派生类,从而查看 类 创建的过程。
DSC0000.png

class MyType(type):  
    def __init__(self,*args,**kwargs):
  

  
        print(&quot;Mytype __init__&quot;,*args,**kwargs)
  

  
    def __call__(self, *args, **kwargs):
  
        print(&quot;Mytype __call__&quot;, *args, **kwargs)
  
        obj = self.__new__(self)
  
        print(&quot;obj &quot;,obj,*args, **kwargs)
  
        print(self)
  
        self.__init__(obj,*args, **kwargs)
  
        return obj
  

  
    def __new__(cls, *args, **kwargs):
  
        print(&quot;Mytype __new__&quot;,*args,**kwargs)
  
        return type.__new__(cls, *args, **kwargs)
  

  
print('here...')
  
class Foo(object,metaclass=MyType):
  

  

  
    def __init__(self,name):
  
        self.name = name
  

  
        print(&quot;Foo __init__&quot;)
  

  
    def __new__(cls, *args, **kwargs):
  
        print(&quot;Foo __new__&quot;,cls, *args, **kwargs)
  
        return object.__new__(cls)
  

  
f = Foo(&quot;Alex&quot;)
  
print(&quot;f&quot;,f)
  
print(&quot;fname&quot;,f.name)
  

  
自定义元类
  类的生成 调用 顺序依次是 __new__ --> __init__ --> __call__
  metaclass 详解文章:http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python 得票最高那个答案写的非常好
反射
  通过字符串映射或修改程序运行时的状态、属性、方法, 有以下4个方法
def getattr(object, name, default=None): # known special case of getattr  
    &quot;&quot;&quot;
  
    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.    &quot;&quot;&quot;
  
    pass
判断object中有没有一个name字符串对应的方法或属性def setattr(x, y, v): # real signature unknown; restored from __doc__  
    &quot;&quot;&quot;
  
    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__  
    &quot;&quot;&quot;
  
    Deletes the named attribute from the given object.
  

  
    delattr(x, 'y') is equivalent to ``del x.y''    &quot;&quot;&quot;
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')
  

  
反射代码示例
  动态导入模块
DSC0001.png

1234import importlib __import__('import_lib.metaclass') #这是解释器自己内部用的#importlib.import_module('import_lib.metaclass') #与上面这句效果一样,官方建议用这个异常处理
  参考 http://www.cnblogs.com/wupeiqi/articles/5017742.html
  例外:抓住所以得错误,不建议在开始使用,可以在没有抓到错误的时候最后使用
  例如:
try:  
    a = 1
  
    print(a)
  
except IndentationError as e:
  
    print(&quot;......出错了&quot;,e)
  
except NameError as e:
  
    print(&quot;......出错了&quot;,e)
  
except Exception as e:
  
    print(&quot;未知错误&quot;,e)
  
else:
  
    print(&quot;一切正常&quot;)
  
finally:
  
    print(&quot;不管有没有错误都会执行&quot;)
  自定义异常:
class wwwException(Exception):  
    def __init__(self,msg):
  
        self.message = msg
  
try:
  
    raise wwwException('数据库连接不上')
  
except wwwException as e:
  
    print(e)
Socket 编程
  参考:http://www.cnblogs.com/wupeiqi/articles/5040823.html

  大多都是在传输程
  ICMP在网络程
  TCP / IP相当于电话拨响了
  HTTP,SMTP ......这些相当于说什么样的话
  作业:开发一个支持多用户在线的FTP程序
  要求:

  •   用户加密认证
  •   允许同时多用户登录
  •   每个用户有自己的家目录 ,且只能访问自己的家目录
  •   对用户进行磁盘配额,每个用户的可用空间不同
  •   允许用户在ftp server上随意切换目录
  •   允许用户查看当前目录下文件
  •   允许上传和下载文件,保证文件一致性
  •   文件传输过程中显示进度条
  •   附加功能:支持文件的断点续传

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-549613-1-1.html 上篇帖子: Delphi使用Python来解码邮件 下篇帖子: linux vim 编写代码python使用tab补全
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表