__xx__这种方法,在Python中均称为魔法方法
1.__init__(self)
该方法的作用是初始化对象
在创建对象时被默认调用,不需要手动调节
self参数不需要开发者传递,解释器会自动将创建的对象传递过去
2.__str__(self)
def __str__(self): return "这是海尔洗衣机的说明书" #运行结果 这是海尔洗衣机的说明书
在打印所创建的对象时会打印出该方法的返回值
代码实例
class washer(): 18 def __init__(self,weight,hight): 19 self.weight = weight 20 self.hight = hight 21 def __str__(self): 22 return "这是海尔洗衣机的说明书" 23 def wash(self): 24 print("洗衣服") 25 print(self) 26 def print_info(self): 27 print("洗衣机的宽度: ",haier.weight," ","洗衣机的> 高度:",haier.hight) 28 29 haier = washer(400,800) 30 print(haier) 31 haier.print_info()