• Python学习记录day8



    title: Python学习记录day8
    tags: python
    author: Chinge Yang
    date: 2017-02-27

    Python学习记录day8

    @(学习)[python]

    1. 静态方法

    @staticmethod装饰器即可把其装饰的方法变为一个静态方法。静态方法,只是名义上归类管理,实际上在静态方法里访问不了类或实例中的任何属性。

    #!/usr/bin/env python
    # _*_coding:utf-8_*_
    '''
     * Created on 2017/2/27 20:18.
     * @author: Chinge_Yang.
    '''
    
    
    class Cat(object):
        def __init__(self, name):
            self.name = name
    
        @staticmethod  # 把eat方法变为静态方法
        def eat(self):
            print("%s is eating" % self.name)
     
    
    d = Cat("bana")
    d.eat()
    

    上面的调用会出以下错误,说是eat需要一个self参数,但调用时却没有传递,没错,当eat变成静态方法后,再通过实例调用时就不会自动把实例本身当作一个参数传给self了。

    staticmethod.py", line 19, in <module>
        d.eat()
    TypeError: eat() missing 1 required positional argument: 'self'
    

    想让上面的代码可以正常工作有两种办法

    1. 调用时主动传递实例本身给eat方法,即d.eat(d)
    2. 在eat方法中去掉self参数,但这也意味着,在eat中不能通过self.调用实例中的其它变量了
    #!/usr/bin/env python
    # _*_coding:utf-8_*_
    '''
     * Created on 2017/2/27 20:18.
     * @author: Chinge_Yang.
    '''
    
    
    class Cat(object):
        def __init__(self, name):
            self.name = name
    
        @staticmethod  # 把eat方法变为静态方法
        def eat():   # 此处去掉self
            print("is eating")
    
    
    d = Cat("bana")
    d.eat()
    

    2. 类方法

    类方法通过@classmethod装饰器实现,其只能访问类变量,不能访问实例变量。

    #!/usr/bin/env python
    # _*_coding:utf-8_*_
    '''
     * Created on 2017/2/27 20:18.
     * @author: Chinge_Yang.
    '''
    
    
    class Cat(object):
        name = "类变量"  # 需要在类中定义变量
        def __init__(self, name):
            self.name = name
    
        @classmethod  # 把eat方法变为类方法
        def eat(self):  # 此处有self
            print("%s is eating" % self.name)
    
    
    d = Cat("bana")
    d.eat()
    

    结果:实例传入的参数不能被使用,使用的是类内部变量。因为没有在类中定义name的话,会有错误提示。

    类变量 is eating
    

    3. 属性方法

    属性方法通过@property把一个方法变成一个静态属性。

    #!/usr/bin/env python
    # _*_coding:utf-8_*_
    '''
     * Created on 2017/2/27 20:18.
     * @author: Chinge_Yang.
    '''
    
    
    class Cat(object):
        def __init__(self, name):
            self.name = name
    
        @property # 把eat方法变为属性方法
        def eat(self):
            print("%s is eating" % self.name)
    
    
    d = Cat("bana")
    d.eat   # 此处不加括号
    

    把一个方法变成静态属性有什么应用场景呢?
    比如 ,你想知道一个航班当前的状态,是到达了、延迟了、取消了、还是已经飞走了, 想知道这种状态你必须经历以下几步:

    1. 连接航空公司API查询
    2. 对查询结果进行解析
    3. 返回结果给你的用户

    因此这个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
    
        @property
        def flight_status(self):
            status = self.checking_status()
            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
    

    既然这个flight_status已经是个属性了, 那给它赋值又如何使用呢?
    需要通过@proerty.setter装饰器再装饰一下,此时 你需要写一个新方法, 对这个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
    
    
        @property
        def flight_status(self):
            status = self.checking_status()
            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):
            status_dic = {
                0 : "canceled",
                1 :"arrived",
                2 : "departured"
            }
            print("33[31;1mHas changed the flight status to 33[0m",status_dic.get(status) )
    
        @flight_status.deleter  #删除
        def flight_status(self):
            print("status got removed...")
    
    f = Flight("CA980")
    f.flight_status
    f.flight_status =  2 #触发@flight_status.setter 
    del f.flight_status #触发@flight_status.deleter 
    

    注意以上代码里还写了一个@flight_status.deleter, 是允许可以将这个属性删除。

    4. 类的特殊成员方法

    4.1 __doc__表示类的描述信息

    class Foo:
        """ 描述类信息 """
     
        def func(self):
            pass
             
    print(Foo.__doc__)
    

    结果:

    描述类信息
    

    4.2 __module____class__

    __module__表示当前操作的对象在那个模块

    __class__表示当前操作的对象的类是什么

    cat lib/c.py

    class Foo(object):
    
        def __init__(self):
            self.name = 'ygqygq2'  
    

    cat index.py

    from lib.c import Foo
    
    obj = Foo()
    print(obj.__module__)  # 输出 lib.c,即:输出模块
    print(obj.__class__)  # 输出 <class 'lib.c.Foo'>,即:输出类
    

    4.3 __init__ 构造方法

    __init__ 构造方法通过类创建对象时,自动触发执行。

    4.4 __del__ 析构方法

    析构方法,当对象在内存中被释放时,自动触发执行。

    注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给Python解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的
    

      

    4.5 __call__ call方法

    对象后面加括号,触发执行。

    class Foo(object):
     
        def __init__(self):
            pass
         
        def __call__(self, *args, **kwargs):
            print('__call__')
     
     
    obj = Foo() # 执行 __init__
    obj()       # 执行 __call__
    
    注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()
    

    4.6 __dict__

    __dict__ 查看类或对象中的所有成员   

    class Province(object):
    
        country = 'China'
    
        def __init__(self, name, count):
            self.name = name
            self.count = count
    
        def func(self, *args, **kwargs):
            print('func')
    
    # 获取类的成员,即:静态字段、方法、
    print(Province.__dict__)
    # 输出:{'__init__': <function Province.__init__ at 0x106a210d0>, 'country': 'China', 'func': <function Province.func at 0x106a21488>, '__doc__': None, '__dict__': <attribute '__dict__' of 'Province' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'Province' objects>}
    
    
    obj1 = Province('HeBei',10000)
    print (obj1.__dict__)
    # 获取 对象obj1 的成员
    # 输出:{'count': 10000, 'name': 'HeBei'}
    
    obj2 = Province('HeNan', 3888)
    print(obj2.__dict__)
    # 获取 对象obj1 的成员
    # 输出:{'count': 3888, 'name': 'HeNan'}
    

    4.7 __str__ 方法

    如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。

    class Foo(object):
     
        def __str__(self):
            return 'ygqygq2'
     
     
    obj = Foo()
    print(obj)
    # 输出:ygqygq2
    

    4.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'] = 'ygqygq2'  # 自动触发执行 __setitem__
    del obj['k1']
    

    结果:

    __getitem__ k1
    __setitem__ k2 ygqygq2
    __delitem__ k1
    

    4.9 __new__ __metaclass__

    class Foo(object):
     
     
        def __init__(self,name):
            self.name = name
     
    f = Foo("ygqygq2")
    print(type(Foo))
    print(type(f))
    

    结果:

    <class 'type'>
    <class '__main__.Foo'>
    

    上述代码中,obj 是通过 Foo 类实例化的对象,其实,不仅 obj 是一个对象,Foo类本身也是一个对象,因为在Python中一切事物都是对象。

    如果按照一切事物都是对象的理论:obj对象是通过执行Foo类的构造方法创建,那么Foo类对象应该也是通过执行某个类的 构造方法 创建。

    print type(f) # 输出:<class 'main.Foo'> 表示,obj 对象由Foo类创建
    print type(Foo) # 输出:<class 'type'> 表示,Foo类对象由 type 类创建
    所以,f对象是Foo类的一个实例,Foo类对象是 type 类的一个实例,即:Foo类对象 是通过type类的构造方法创建。

    那么,创建类就可以有两种方式:
    1). 普通方式

    class Foo(object):
      
        def func(self):
            print('hello')
    

    2). 特殊方式

    def func(self):
        print('hello')
    
    Foo = type('Foo',(object,), {'func': func})
    
    #type第一个参数:类名
    #type第二个参数:当前类的基类
    #type第三个参数:类的成员
    

    加上构造方法,所以 ,类是由 type 类实例化产生。

    那么问题来了,类默认是由 type 类实例化产生,type类中如何实现的创建类?类又是如何创建对象?
    答:类中有一个属性 __metaclass__,其用来表示该类由谁来实例化创建,所以,我们可以为 __metaclass__ 设置一个type类的派生类,从而查看类 创建的过程。

    类的生成 调用 顺序依次是 __new__ --> __call__ --> __init__

  • 相关阅读:
    最近学习下,nohup和&的区别
    java 关键字
    iOS之事件穿透
    排序算法——快速排序
    分布式-选举算法
    分布式选举算法
    SolrCloud 分布式集群部署步骤
    linux 启动两个tomcat
    solr安装-tomcat+solrCloud构建稳健solr集群
    JAVA 中BIO,NIO,AIO的理解
  • 原文地址:https://www.cnblogs.com/ygqygq2/p/6503693.html
Copyright © 2020-2023  润新知