Python __str__函数
class Cat: def __init__(self,_name): self.name = _name def __str__(self): return "i am %s"%self.name def show(self): print("name is %s"%self.name) tom = Cat("tom") tom.show() print(tom) print("------------"); lanmao = Cat("lanpang") lanmao.show() print(lanmao)
__str__函数要求有返回值,必须有return, __str__函数功能是将对象字符串化
python类中所有的属性和方法默认都是Public,可以在函数外访问
class Cat: def __init__(self,_name): self.name = _name self.fish = [] def __str__(self): #__str必须返回一个字符串,不能是其他任何值 #注意列表的字符串化 return "i am %s and i eat %s ."%(self.name,str(self.fish)) def eat(self,_fish): self.fish.append(_fish.name) class Fish: def __init__(self,_name): self.name = _name tom = Cat("tom") fish = Fish("鲫鱼") tom.eat(fish) print(tom)