欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python hasattr/getattr/setattr/instancemethod/classmethod/staticmethod

程序员文章站 2022-07-15 16:50:26
...

描述:含hasattr/getattr/setattr/instancemethod/classmethod/staticmethod

instancemethod: 普通方法,供实例调用

classmethod: 类方法,不需实例化对象,供实例和类调用

staticmethod: 与类中其他方法、属性无关的方法,供类、实例调用

 

# -*- coding: utf8 -*-


class First(object):
    name = 'first class name'

    def instance_func(self):
        print("class first instance func")

    @classmethod
    def class_func(cls):
        print('class first class func')
        print('class first attr name: ', cls.name)

    @staticmethod
    def statuc_func():
        print('class first static func')


if __name__ == '__main__':
    a = First()
    print("* * " * 30)
    print(hasattr(a, 'name'))
    print(getattr(a, 'name'))
    print(setattr(a, 'name', '123'))
    print(getattr(a, 'name'))

    print("* * " * 30)
    a.instance_func()
    a.class_func()
    a.statuc_func()
    First.class_func()
    First.statuc_func()
    print("* * "*30)

输出:

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
True
first class name
None
123
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
class first instance func
class first class func
class first attr name:  first class name
class first static func
class first class func
class first attr name:  first class name
class first static func
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 

相关标签: 开发