微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python 创建类的语法

class Cat:
    def __init__(self, new_name):
        self.name = new_name

    def eat(self):
        print("%s爱吃鱼" % self.name)


tom = Cat("tom")
tom.eat()

tom2 = Cat("tom2")
tom2.eat()

 

class Person:
    def __init__(self, name, weight):
        self.name = name
        self.weight = weight

    def __str__(self):

        return '我的名字叫 %s 体重 %.2f ' % (self.name, self.weight)

    def run(self):
        print("跑步锻炼身体")
        self.weight -= 0.5

    def eat(self):
        print("吃东西容易长胖")
        self.weight += 1


ming = Person("小明", 75.0)
ming.run()
ming.eat()
print(ming)

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐