python普通方法、类方法、静态方法

参考:http://blog.csdn.net/chendong_/article/details/52180310

开始

# -*-coding:utf-8-*-
# 普通方法,类方法,静态方法的区别

__metaclass__ = type


class Tst:
    name = 'tst'

    data = 'this is data'

    # 普通方法
    def normalMethod(self, name):
        print self.data, name

    # 类方法,可以访问类属性
    @classmethod
    def classMethod(cls, name):
        print cls.data, name

    # 静态方法,不可以访问类属性
    @staticmethod
    def staticMethod(name):
        print name
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

测试

  • 三种方法都可以通过实例来调用,但是静态方法和类方法无法访问实例属性,所以更改了tst.data仅对普通方法起了作用
tst = Tst()
tst.data = 'this is new'
tst.normalMethod('name')
tst.staticMethod('name')
tst.classMethod('name')

#结果
this is new name
name
this is data name
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

区别

  • 普通方法不能通过类名调用,但是静态方法和类方法是可以的
# error普通方法必须通过实例调用
# Tst.normalMethod('name')
Tst.classMethod('name')
Tst.staticMethod('name')

#结果
this is data name
name
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

总结

  • 普通方法,可以通过self访问实例属性,三种方法都可以通过实例来调用
def normalMethod(self,data)
   
   
  • 1
  • 1
  • 类方法,可以通过cls访问类属性
@classmethod
def classMethod(cls,data)
   
   
  • 1
  • 2
  • 1
  • 2
  • 静态方法,不可以访问,类属性通过传值的方式
@staticmethod
def staticMethod(data)
   
   
  • 1
  • 2
  • 1
  • 2

实例方法只能被实例对象调用,静态方法(由@staticmethod装饰的方法)、类方法(由@classmethod装饰的方法),可以被类或类的实例对象调用。
实例方法,第一个参数必须要默认传实例对象,一般习惯用self。
静态方法,参数没有要求。
类方法,第一个参数必须要默认传类,一般习惯用cls。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值