1、class Animal: #首先我们要新建一个类,注意这个类要大写。这里创建一个动物类。
2、class Animal: def __init__(self): #接着就是初始化设置属性,记得要第一个参数里面写入self。
3、class Animal: def __init__(self, name, weight): self.name = name self.weight = weight #先开始定义参数需要多少个,然后让对象调用这些参数。
4、class Animal: def __init__(self, name, weight): self.name = name self.weight = weight def __str__(self): return "The weight of %s is %s now." %(self.name, self.weight) #这里定义一下对象要返回的字符串,记得必须是字符串。
5、class Animal: def __init__(self, name, weight): self.name = name self.weight = weight def __str__(self): return "The weight of %s is %s now." %(self.name, self.weight) def run(self): self.weight -= 2 #这里设置如果动物跑步那就减少重量,这里是可以调用属性的。
6、class Animal: def __init__(self, name, weight): self.name = name self.weight = weight def __str__(self): return "The weight of %s is %s now." %(self.name, self.weight) def run(self): self.weight -= 2 def eat(self): self.weight += 4 #再设置一个方法,同样可以调用属性。
7、class Animal: def __init__(self, name, weight): self.name = name self.weight = weight def __str__(self): return "The weight of %s is %s now." %(self.name, self.weight) def run(self): self.weight -= 2 def eat(self): self.weight += 4 tiger = Animal("Tiger", 10)tiger.run()tiger.eat()print(tiger)#然后我们可以定义对象了,记得传入参数,最后打印一下结果。
8、class Animal: def __init__(self, name, weight): self.name = name self.weight = weight def __str__(self): return "The weight of %s is %s now." %(self.name, self.weight) def run(self): self.weight -= 2 def eat(self): self.weight += 4 tiger = Animal("Tiger", 10)tiger.run()tiger.eat()print(tiger)rabbit = Animal("Rabbit", 5)rabbit.run()print(rabbit)#再定义一个对象,这里可以看出没有调用的方法是不会自动运行的。
9、class Animal: def __init__(self, name, weight): self.name = name self.weight = weight def __str__(self): return "The weight of %s is %s now." %(self.name, self.weight) def run(self): self.weight -= 2 def eat(self): self.weight += 4 tiger = Animal("Tiger", 10)tiger.run()tiger.eat()rabbit = Animal("Rabbit", 5)rabbit.run()print(rabbit)print(tiger)#这里调换一下位置,可以看出对象之间是不会影响的。