zoukankan      html  css  js  c++  java
  • Python入门学习笔记11(静态方法、类方法与属性方法)

    1.静态方法

    静态方法通过@staticmethod装饰,静态方法无法访问类变量和实例变量,可以认为静态方法是一种归类在某个类之下,但是实际上与该类没有直接关系的方法,可通过类名调用。

    例如一些工具集就是通过静态方法来实现的

    class Sample(object):
        CC = "class"
    
        def __init__(self,name):
            self.name = name
    
        @staticmethod
        def staticFunc():
            # print(CC)#无法访问
            print("hello")
    

    如果静态方法一定要访问实例变量的话,就必须将实例作为参数传入。

    2.类方法

    类方法使用@classmethod装饰,只能访问类变量。

    类方法不需要self参数,取而代之的是一个表示自身类的cls参数.

    类方法可以使用类名直接调用

    当实例变量与类变量重名时,可以利用实例调用类方法来强制访问类变量

    class Sample(object):
        CC = "class"
        def __init__(self):
            self.CC = "self"
    
        @classmethod
        def classFunc(cls):
            print(cls.CC)
    
        def Func(self):
            print(self.CC)
    

    3.属性方法

    属性方法使用@property装饰。

    属性函数的作用类似于C#中的属性,用于将私有变量进行封装。

    根据需要可以进行赋值校验、转换、设置只读等操作。

    定义一个私有变量,使用@property修饰一个getter进行读取操作。

    使用@xx.setter定义设置操作,这就相当于C#中属性的get set。

    class Sample(object):
        def __init__(self):
            self.__age = None
    
        @property
        def age(self):
            return self.__age
        #不定义setter就是一个只读属性
        @age.setter
        def age(self,age):
            if type(age) is int:
                self.__age = age
            else:
                raise ValueError("不是数字")
    
    SS = Sample()
    #属性方法使用括号传值会报错
    #SS.age(18)
    #属性方法直接赋值
    SS.age = 18
    print(SS.age)
    

      

  • 相关阅读:
    三大主流负载均衡软件对比(LVS+Nginx+HAproxy)
    nginx 提示the "ssl" directive is deprecated, use the "listen ... ssl" directive instead
    centos安装nginx并配置SSL证书
    hadoop创建目录文件失败
    The server time zone value 'EDT' is unrecognized or represents more than one time zone.
    脚本启动SpringBoot(jar)
    centos做免密登录
    数据库远程连接配置
    Bash 快捷键
    TCP三次握手四次断开
  • 原文地址:https://www.cnblogs.com/Hexdecimal/p/9365437.html
Copyright © 2011-2022 走看看