zoukankan      html  css  js  c++  java
  • python学习笔记之面向对象中的静态方法、类方法、属性方法总结

    • 静态方法
    • 类方法
    • 属性方法

    一、静态方法

    可以利用@staticmethod装饰器把一个方法变成一个静态方法。静态方法不可以方法实例变量或者类变量,也就是说不可以使用self.属性这样子调用实例属性了。其实静态方法就和类本身没什么关系了,它和类

    唯一的关联就是需要通过类名来调用这个方法。

    错误调用方式:

    class Dog(object):
        def __init__(self,name):
            self.name = name
        @staticmethod #把eat方法变为静态方法
        def eat(self):
            print("%s is eating" % self.name)
    d = Dog("ChenRonghua")
    d.eat()

    上面的调用会出以下错误,说是eat需要一个self参数,但调用时却没有传递,没错,当eat变成静态方法后,再通过实例调用时就不会自动把实例本身当作一个参数传给self了。

    正确调用方法:

    class Dog(object):
        def __init__(self,name):
            self.name = name
        @staticmethod
        def eat():
            print(" is eating")
    d = Dog("ChenRonghua")
    d.eat()

    或者:

    lass Dog(object):
        def __init__(self,name):
            self.name = name
        @staticmethod #把eat方法变为静态方法
        def eat(self):
            print("%s is eating" % self.name)
    d = Dog("ChenRonghua")
    d.eat(d)

    二、类方法

    类方法是用@classmethod装饰器来实现的,类方法只能访问类变量,不能访问实例变量。

    class Dog(object):
        def __init__(self,name):
            self.name = name
     
        @classmethod
        def eat(self):
            print("%s is eating" % self.name)
     
    d = Dog("ChenRonghua")
    d.eat()
    

    上面的name是构造方法里面定义的,是一个实例变量,类方法是不能访问的。所以会报错:dog没有name属性

    对比下面的:

    class Dog(object):
        name = "我是类变量"
        def __init__(self,name):
            self.name = name
     
        @classmethod
        def eat(self):
            print("%s is eating" % self.name)
     
     
    d = Dog("ChenRonghua")
    d.eat()
     
     
    #执行结果
     
    我是类变量 is eating
    

    三、属性方法

    属性方法就是通过@property把一个方法变成静态属性

    class Dog(object):
     
        def __init__(self,name):
            self.name = name
     
        @property
        def eat(self):
            print(" %s is eating" %self.name)
     
     
    d = Dog("ChenRonghua")
    d.eat()
    

      调用会出以下错误, 说NoneType is not callable, 因为eat此时已经变成一个静态属性了, 不是方法了, 想调用已经不需要加()号了,直接d.eat就可以了

    正确的使用:

    d = Dog("ChenRonghua")
    d.eat
     
    输出
     ChenRonghua is eating
    

      

  • 相关阅读:
    C#windows向窗体传递泛型类
    phoenix与spark整合
    phoenix创建二级索引
    git
    socket详解
    切片
    通过串口读写数据
    Python 跳出多重循环
    Python从json中提取数据
    Python 字典
  • 原文地址:https://www.cnblogs.com/mesunyueru/p/9043290.html
Copyright © 2011-2022 走看看