• python 中的 @ 符号


    1 . 修饰函数

    看装饰器这一节

    https://www.cnblogs.com/xumaomao/articles/10984271.html

    2. @staticmethod

    相当于C++里的静态函数

    #!/usr/bin/ env python
    # -*- coding:utf-8 -*-
    
    class Student(object):
        #类属性
        name = 'fdzwdt'
        def __init__(self,name):
            #实例对象属性
            self.name = name
        
        #实例方法,只能由实例对象来调用
        def get_name_ins(self):
            return self.name
        
        #类方法,可以通过类来调用,也可以通过实例对象调用
        @classmethod
        def get_name_cls(cls):
            return cls.name
        
        #静态方法,可以通过类来调用,也可以通过实例对象调用
        #主要功能就是对__init__构造函数进行重载
        @staticmethod
        def get_name_sta(name):
            return Student(name).name
    st = Student('weidt')
    print('ins_name:'+st.get_name_ins())
    print('cls_name:'+Student.get_name_cls())
    print('sta_name:'+Student.get_name_sta('wdt'))

    3. @classmethod

    classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    class A(object):
        bar = 1
        def func1(self):  
            print ('foo') 
        @classmethod
        def func2(cls):
            print ('func2')
            print (cls.bar)
            cls().func1()   # 调用 foo 方法
     
    A.func2()               # 不需要实例化

    输出结果为:

    func2
    1
    foo

    4. 修饰类

    1. 修改类函数。

    场景: 如果要给一个类的所有方法加上计时,并打印出来

    # -*- coding:utf-8 -*-
    import time
    def time_it(fn):
        "Example of a method decorator"
        def decorator(*args, **kwargs):
            t1=time.time()
            ret = fn(*args, **kwargs)
            print('		%d seconds taken for %s'%(time.time()-t1, fn.__name__))
            return ret
    
        return decorator
    
    def class_decorator(*method_names):
        def class_rebuilder(cls):
            "The class decorator example"
            class NewClass(cls):
                "This is the overwritten class"
                def __getattribute__(self, attr_name):
                    attr_val = super(NewClass, self).__getattribute__(attr_name)
                    if callable(attr_val) and attr_name in method_names:
                        return time_it(attr_val)
                    return attr_val
    
            return NewClass
        return class_rebuilder
    
    @class_decorator('first_method', 'second_method')
    class MySecondClass(object):
        """
        This class is decorated
        """
        def first_method(self, *args, **kwargs):
            print("	this is a the MySecondClass.first_method")
        time.sleep(2)
    
        def second_method(self, *args, **kwargs):
            print("	this is the MySecondClass.second_method")
        time.sleep(1)
    
    if __name__ == "__main__":
        print("::: With a decorated class :::")
        z = MySecondClass()
        z.first_method()
        z.second_method()

    输出:

    ::: With a decorated class :::
        this is a the MySecondClass.first_method
            0 seconds taken for first_method
        this is the MySecondClass.second_method
            0 seconds taken for second_method

    2. 增加类成员

    场景:比如统一给所有的模型增加id, created_time属性

    # -*- coding:utf-8 -*-
    import time
    def cd(cls):
        def init(*args, **kwargs):
            cls_obj = cls(*args, **kwargs)
            setattr(cls_obj, 'id', time.time())
            return cls_obj
        return init
    @cd
    class A(object):
        def __init__(self, name, age, sex='f'):
            self.name=name
            self.age=age
            self.sex=sex
        def s(self):
            print self.id
    
    if __name__=='__main__':
        print type(A)#<type 'function'>
        a=A('Alice', 22)
        print type(a)#<class '__main__.A'>
        print a#<__main__.A object at 0x7fe617baa690>
        print a.name, a.age, a.sex#Alice 22 f
        a.s()

    输出

    <type 'function'>
    <class '__main__.A'>
    <__main__.A object at 0x1005f4bd0>
    Alice 22 f
    1627034597.78
  • 相关阅读:
    java 截取pdf
    webService 发送soap请求,并解析返回的soap报文
    常用网址
    扫描文件夹下代码行数
    CodeMIrror 简单使用
    常用 linux 命令(部分)
    windows下RabbitMQ 监控
    一定要写的日志
    创业思路
    10月9日后计划
  • 原文地址:https://www.cnblogs.com/xumaomao/p/15046438.html
Copyright © 2020-2023  润新知