类与对象
类继承自object,一般称之为“属性”。
class Hero(object):
类函数第一参数必须为self,一般称之为“方法”。
def magicAttack(self, times = 1):
具体属性与方法,可以通过help(Hero)来查看。
示例
Python 2.7.10 (default, Jul 15 2017, 17:16:57)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>> class Hero(object):
... health = 100
... magic = 60
... magicAttackStep = 10
... def magicAttack(self, times = 1):
... if (self.magic - times * self.magicAttackStep >= 0):
... self.magic -= times * self.magicAttackStep
... return True
... return False
...
>>>
>>> ZhaoYun = Hero()
>>> ZhaoYun.health
100
>>> ZhaoYun.magic
60
>>> ZhaoYun.magicAttack()
True
>>> ZhaoYun.magic
50
>>> ZhaoYun.magicAttack(3)
True
>>> ZhaoYun.magic
20
>>> ZhaoYun.magicAttack(3)
False
>>> ZhaoYun.magic
20
>>>