python类方法和静态方法简单理解

使用@classmethod修饰的为类方法,使用 @staticmethod修饰的为静态方法,具体使用如下:

类方法

class Person:
	hair='black'
	def __init__(self,name,age):
			self.name=name
			self.age=age
	def  say(self,content):
			print(content)
	@classmethod
	def classfunc(cls):
		print("classfunc:",cls.hair)
	@staticmethod
	def staticfunc(cls):
		print("staticfunc",cls)
me=Person('me',10)
me.hair='red'
print(Person.hair)
Person.classfunc()
print('------------')
print(me.hair)
me.classfunc()

输出如下:

black
classfunc: black
------------
red
classfunc: black

可以看到,即使使用实例对象(me)去调用类方法,该方法第一个参数自动绑定的还是该类(Person)。

静态方法

class Person:
	hair='black'
	def __init__(self,name,age):
			self.name=name
			self.age=age
	def  say(self,content):
			print(content)
	@classmethod
	def classfunc(cls):
		print("classfunc:",cls.hair)
	@staticmethod
	def staticfunc(cls):
		print("staticfunc",cls)
me=Person('me',10)
Person.staticfunc('Person')
Person.staticfunc()

输出如下:

staticfunc Person
Traceback (most recent call last):
  File "test.py", line 16, in <module>
    Person.staticfunc()
TypeError: staticfunc() missing 1 required positional argument: 'cls'

可见静态方法没有自动绑定第一个参数,故需要传参。利用实例对象me调用同理。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值