zoukankan      html  css  js  c++  java
  • python _str_方法

    _str_方法:

    使用:如:

    class Car:
        def __init__(self,newWheelNum,newColor):
            self.wheelNum=newWheelNum
            self.color=newColor
        def __str__(self):
            msg='嘿。。我的颜色是'+self.color,+'我有'+ int(self.wheelNum)+'个轮胎'
            return msg
        def move(self):
            print('车在跑,目标:夏威夷')
    
    BMW=Car(4,'白色')
    print(BMW)

    总结:在python中方法如果是_xxxx_()的,那么就有特殊的功能,因此叫做‘’魔法‘’方法

    当使用print输出对象的时候,只要自己定义了_str_(self)方法,那么就会打印从这个方法中return的数据

    class Cat:
        #初始化对象
        def __init__(self,name,age):
            self.name=name
            self.age=age
        def __str__(self):
            return '%s的年龄是:%d'%(self.name,self.age)
        #方法
        def eat(self):
            print('猫在吃鱼...')
        def drink(self):
            print('猫正在喝kele...')
        def introduce(self):
            print('%s的年龄是:%d'%(self.name,self.age))
    #创建一个对象
    tom=Cat('汤姆',40)
    lanmao=Cat('蓝猫',10)
    print(tom)
    print(lanmao)

      

    我是kelly-凯莉 每天努力一点点,幸运就多一点点
  • 相关阅读:
    spark java wordCount实例
    SpringMVC 商城项目
    jstl 遍历数据
    jquery 方法总结
    8ch
    7ch
    使用vuex实现组件间传值
    Vue父子组件之间传值
    从浏览器输入URL地址到最终页面渲染完成,发生了什么?
    数组去重
  • 原文地址:https://www.cnblogs.com/kelly11/p/11857611.html
Copyright © 2011-2022 走看看