码迷,mamicode.com
首页 > 编程语言 > 详细

Python类(六)-静态方法、类方法、属性方法

时间:2018-01-28 11:16:17      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:set   def   author   log   foo   pre   inf   object   报错   

  • 静态方法

通过@staticmethod来定义,静态方法在类中,但在静态方法里访问不了类和实例中的属性,但静态方法需要类来调用

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

class Person(object):
    def __init__(self,name):
        self.name = name

    @staticmethod
    def eat(self,food):
        print("%s is eating %s"%(self.name,food))

if __name__ == ‘__main__‘:
    p = Person(‘John‘)
    p.eat(‘meat‘)

 运行,报错

技术分享图片

把eat方法的参数去掉,直接打印,可以直接调用

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

class Person(object):
    def __init__(self,name):
        self.name = name

    @staticmethod
    def eat():
        print("John is eating")

if __name__ == ‘__main__‘:
    p = Person(‘John‘)
    p.eat()

运行结果

技术分享图片

如果要给eat()传参数的话,可以把实例化的Person传入

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

class Person(object):
    def __init__(self,name):
        self.name = name

    @staticmethod
    def eat(self):
        print("%s is eating"%self.name)

if __name__ == ‘__main__‘:
    p = Person(‘John‘)
    p.eat(p)

 运行结果

技术分享图片

  • 类方法

类方法通过@classmethod来定义

类方法只能访问类变量,不能访问实例变量

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

class Person(object):
    name = ‘Jack‘
    def __init__(self,name):
        self.name = name

    @classmethod
    def eat(self):
        print("%s is eating"%self.name)

if __name__ == ‘__main__‘:
    p = Person(‘John‘)
    p.eat()

运行结果

技术分享图片

传入了实例变量John,但打印的却是Jack

因为类方法不能访问实例变量,所以类方法访问了类里的类变量

  • 属性方法

通过@property来定义属性方法

把类中的方法变为静态属性

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

class Person(object):
    def __init__(self,name):
        self.name = name

    @property
    def eat(self):
        print("%s is eating"%self.name)

if __name__ == ‘__main__‘:
    p = Person(‘John‘)
    p.eat

 按照调用属性的方法来调用属性方法

技术分享图片

如果想给属性方法传参数的话,要使用setter

Python类(六)-静态方法、类方法、属性方法

标签:set   def   author   log   foo   pre   inf   object   报错   

原文地址:https://www.cnblogs.com/sch01ar/p/8368508.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!