class Cat: #类名用大驼峰 """定义了一个Cat类""" #属性 #方法 def eat(self): print("猫在吃鱼") def drink(self): print("猫在喝水") def introduce(self): #print("%s的年龄是%s"%(tom.name,tom.age)) print("%s的年龄是%s"%(self.name,self.age)) #创建一个对象 tom = Cat() tom.eat() tom.drink() #给tom的对象添加两个属性 tom.name = "汤姆" tom.age = 18 lanmao = Cat() lanmao.name = "蓝猫" lanmao.age = 20 lanmao.introduce()
class Cat: #类名用大驼峰 """定义了一个Cat类""" #属性 def __init__(self,new_name,new_age): #初始化对象, 创建对象后自动调用,返回创建对象的引用。称为魔法方法 self.name = new_name self.age = new_age def __str__(self): return "%s的年龄是%d"%(self.name,self.age) #方法 def eat(self): print("猫在吃鱼") def drink(self): print("猫在喝水") def introduce(self): #print("%s的年龄是%s"%(tom.name,tom.age)) print("%s的年龄是%s"%(self.name,self.age)) #创建一个对象 tom = Cat("汤姆",18) tom.eat() tom.drink() #给tom的对象添加两个属性 #tom.name = "汤姆" #tom.age = 18 lanmao = Cat("蓝猫",20) #lanmao.name = "蓝猫" #lanmao.age = 20 lanmao.introduce() print(tom) # 没有__str__()的时候打印的是引用地址,有,打印str的返回值 print(lanmao)
原文:https://www.cnblogs.com/ql0302/p/11278701.html