码迷,mamicode.com
首页 > 其他好文 > 详细

静态方法和类方法

时间:2018-08-22 01:14:28      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:hit   cme   python   @class   ssm   身高   ado   pytho   method   

1、类方法:@classmethod

如下例子:

class Hero(object):
	__height = 1     # 英雄高度

	def __init__(self, name, ad, ap):   # 初始化属性
		self.__name = name
		self.__ad = ad
		self.__ap = ap

	@classmethod
	def set_height(cls, new_height):    # 配置英雄的身高
		cls.__height = new_height

	@property
	def hit_ad(self):          # 返回英雄的伤害
		return self.__ad

	@hit_ad.setter
	def hit_ad(self, va):    # 添加暴击效果
		self.__ad = self.__ad * va

	@property
	def hero_name(self):
		return self.__name


hero = Hero("chenAdong", 100, 100) 
print "%s 输出了 %s 点物理伤害" % (hero.hero_name, hero.hit_ad)

>>>chenAdong 输出了 100 点物理伤害 # 输出结果

  如上,类方法可以用来修改静态属性;

2、静态方法:@staticmethod

先举例子:

class Hero(object):
	def __init__(self, name):
		self.__name = name
		print "hero_name: %s" % self.__name

	@staticmethod
	def create_hero():
		Hero("chenAdong")


Hero.create_hero()
>>> hero_name: chenAdong

  如上:在类中,定义方法需要传给默认参数self,使用静态方法,则不用,但可以传其他参数;

静态方法和类方法

标签:hit   cme   python   @class   ssm   身高   ado   pytho   method   

原文地址:https://www.cnblogs.com/chenadong/p/9515318.html

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