zoukankan      html  css  js  c++  java
  • 静态方法、类方法、属性方法

    静态方法:通过加@staticmethod实现,只是名义上归类管理,实际上在静态方法里访问不了类或实例中的任何属性。

    class Person(object):
        @staticmethod
        def person_speak(obj):
            print('I like Hiphop!')
    
    me = Person()
    me.person_speak(me)
    Person.person_speak(me)
    
    # I like Hiphop! 
    # I like Hiphop! 

    类方法:通过加@classmethod实现,只能访问类变量,不能访问实例变量。

    class Person(object):
        sex = 'man'
        def __init__(self, sex):
            self.sex = sex
        # @classmethod
        def hello(self):
            print('I am {}'.format(self.sex))
    
    me = Person('woman')
    me.hello()
    
    # I am woman
    # 去掉装饰器的注释后,输出
    # I am man

    属性方法:通过加@property实现,把一个方法变成静态属性

    class Person(object):
        n = 1
        @property
        def hello(self):
            print(self.n)
    
    me = Person()
    me.hello

    # 输出
    # 1

    一般的属性都可以赋值,但是属性方法的赋值特殊处理

    class Person(object):
        def __init__(self):
            self.__n = 1
        @property
        def hello(self):
            return self.__n
        @hello.setter
        def hello(self, n):
            self.__n = n
    
    
    me = Person()
    print(me.hello) # 1
    me.hello = 666
    print(me.hello) # 666

    同理,也可以删除

    class Person(object):
        def __init__(self):
            self.__n = 1
        @property
        def hello(self):
            return self.__n
        @hello.setter
        def hello(self, n):
            self.__n = n
        @hello.deleter
        def hello(self):
            del self.__n
    
    me = Person()
    me.hello = 666
    del me.hello
    me.hello
    
    Traceback (most recent call last):
      File "oop.py", line 19, in <module>
        me.hello
      File "oop.py", line 8, in hello
        return self.__n
    AttributeError: 'Person' object has no attribute '_Person__n'
  • 相关阅读:
    理解爬虫原理
    中文词频统计与词云生成
    复合数据类型,英文词频统计
    字符串操作、文件操作,英文词频统计预处理
    了解大数据的特点、来源与数据呈现方式
    作业四-结对项目
    大数据应用期末总评
    分布式文件系统HDFS 练习
    安装Hadoop
    《恶魔人crybaby》豆瓣短评爬取
  • 原文地址:https://www.cnblogs.com/allenzhang-920/p/9393357.html
Copyright © 2011-2022 走看看