一、对象在文本中的输出
class Person:
def __init__(self,name,agg,live_value,money):
self.name=name
self.agg=agg
self.live_value=live_value
self.money=money
def describe():
print('%s的攻击力是%s'%(self.name,self.agg))
p=Person('bob',10,10000,100)
b=Person('tony',10,10000,100)
print(p.describe())
print(b.describe())
%s可以将要输出的内容转化为字符串形式输出,而后面的属性就是我们要输出的内容,也是对位输出。
二、init函数详解
class Person:
def __init__(self,name,agg,live_value,money):
self.name=name
self.agg=agg
self.live_value=live_value
self.money=money
def describe():
print('%s的攻击力是%s'%(self.name,self.agg))
p=Person('bob',10,10000,100)
b=Person('tony',10,10000,100)
print(p.describe())
print(b.describe())
这个函数可以叫做__init__方法,也称之为构造方法。
__init__函数是面向对象编程中的特殊方法,当创建一个类的实例时它可以自动调用。
自动调用的意思解释:
class Person:
def __init__(self,name,agg,live_value,money):
self.name=name
self.agg=agg
self.live_value=live_value
self.money=money
def describe():
print('%s的攻击力是%s'%(self.name,self.agg))
p=Person('bob',10,10000,100)
b=Person('tony',10,10000,100)
print(p.describe())
print(b.describe())
看上面这个函数,大家知道Person这个类里面有两个函数,在上一章讲过这一个类就是一个个体,那么我们要调用这个个体里面的函数就需要有一个中介,那么这个中介就是self,我们通过面向对象编程的self实现自动回调,才能赋予这个对象使用这个类里面的属性的能力,相当于我赋予我这个对象能够使用武器的能力,当然这个解释只是为了方便理解我把它抽象为一个过程。事实上这个self是必不可少的,大家记住就行了,对于这个self我不做过多解释。如果想更加了解__init__函数,详情参考: