• python学习笔记(五)——静态方法、类方法、运算符重载


    我们都知道类名是不能够直接调用类方法的。在C++中,把成员方法声明为 static 静态方法后可以通过类名调用。同样的在python中也可以通过定义静态方法的方式让类名直接调用。

    静态方法

    使用 @staticmethod 后紧跟着的方法为静态方法。

    class test:
        var = 10
        @staticmethod
        def func():
            print("var = ",test.var)
    
    ts=test()		#实例化
    ts.func()		#使用对象调用静态方法
    test.func()		#使用类名调用静态方法
    
    输出:
    var =  10
    var =  10
    

    在静态方法的参数列表中没有 self ,也就意味着它不可以调用我们类中的实例属性和实例方法。但是可以通过我们的类名调用类属性。

    类方法

    使用 @classmethod 后面紧跟着的方法为类方法。同样,类方法也支持类名访问和实例访问。

    class test:
        var = 10
        @classmethod
        def mytest(cls):    # cls 代表类名
            print("这是类方法")
    
    ts=test()			#实例化
    ts.mytest()			#使用对象调用类方法
    test.mytest()		#使用类名调用类方法
    
    输出:
    这是类方法
    这是类方法
    

    在类方法的参数列表中 cls 是类名的代表,也就是说,在类方法中可以调用静态方法和类属性。

    class test:
        @staticmethod
        def func():
            print("这是静态方法")
        @classmethod
        def mytest(cls):
            print("这是类方法")
            test.func()
    
    ts=test()
    ts.mytest()
    test.mytest()
    
    输出:
    这是类方法
    这是静态方法
    这是类方法
    这是静态方法
    

    并且,由于静态方法是全局的,也是可以调用类方法的。

    运算符重载

    在python中形如 __xxx__ 的方法不需要我们手动调用,在运行至条件发生时会自动调用。比如我们的 __init____del__ 等。

    我们现在重载 “+” 运算,使其对象相加只加年龄,那么就可以这么写。

    class test:
        def __init__(self, name, age):
            self.name = name
            self.age  = age
        def __add__(self, other):		#重载
            return self.age + other.age
    
    ts1 = test("张三",18)
    ts2 = test("李四",20)
    age = ts1 + ts2
    print(age)
    
    输出:
    38
    

    在 python 中调用 print() 打印实例对象时会调用__str__(),输出一些信息。如果__str__()中有返回值,就会打印其中的返回值。

    ts = test("张三",18)
    print(ts)
    
    输出:
    <__main__.test object at 0x00000272E61C35F8>
    

    我们现在重载 str 使得调用print() 时输出我们想要的信息。实例名 + 类型。

    class test:
        def __init__(self, name, age):
            self.name = name
            self.age  = age
        def __str__(self):
            return '名字是%s,类型是%s'%(self.name,type(self))
    
    ts = test("张三",18)
    print(ts)
    
    输出:
    名字是张三,类型是<class '__main__.test'>
    
  • 相关阅读:
    8月4日
    8月3日 hive配置
    8月2日
    8月1日
    7月31日
    7月30日
    7月29日
    7月28日
    第六周总结
    重大技术需求进度报告一
  • 原文地址:https://www.cnblogs.com/TaoR320/p/12680114.html
Copyright © 2020-2023  润新知