zoukankan      html  css  js  c++  java
  • python中类的魔法方法

    __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()         

                                                                                                       

    笨鸟先飞
  • 相关阅读:
    POJ2155 Matrix
    POJ3469 Dual Core CPU
    洛谷P1469找筷子
    CodeForces 97D. Robot in Basement
    UVa11542 Square
    清澄 A1485. Catch The Penguins 抓企鹅
    Bzoj2595: [Wc2008]游览计划
    HDU4085 Peach Blossom Spring
    CodeForces 333E. Summer Earnings
    洛谷P3389 【模板】高斯消元法
  • 原文地址:https://www.cnblogs.com/zoutingrong/p/13681452.html
Copyright © 2011-2022 走看看