首页 > 其他 > 详细

面向对象

时间:2019-07-31 21:03:18      阅读:108      评论:0      收藏:0      [点我收藏+]

 

 

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!