The first day of Object-Oriented

Classes and Objects: Class is equivalent to a model airplane drawings, is responsible for creating objects.

                  Objects created out of a specific type of existence, can be used directly, there are objects in the program development have first class

Characterized called attribute, called behavioral methods, class defines the properties and methods.

class Cat:
    def eat(self):
        print("小猫爱吃鱼")
    def drink(self):
        print("小猫要喝水")

#创建猫对象
t=Cat()
t.eat()
t.drink()

 

class Cat:
    def eat(self):
        print("%s爱吃鱼"%self.name)
    def drink(self):
        print("%s要喝水"%self.name)

#创建猫对象
t=Cat()
t.name="小狗"
t.eat()
t.drink()

class Cat:
    def __init__(self):
        print("初始化方法")

#使用类名()创建对象的时候会自动调用初始化方法__init__
t=Cat()

class Cat:
    def __init__(self):
        print("初始化方法")
        #self.属性名=属性的初始值
        self.name="小猫"
    def eat(self):
        print("%s爱吃鱼"%self.name)
#使用类名()创建对象的时候会自动调用初始化方法__init__
t=Cat()
t.eat()

 

class Cat:
    def __init__(self,new_name):
        print("初始化方法")
        #self.属性名=属性的初始值
        self.name=new_name
    def eat(self):
        print("%s爱吃鱼"%self.name)

t=Cat("小猫")
t.eat()

class Person:
    def __init__(self,name,weight):
        #self.属性=形参
        self.name=name
        self.weight=weight
    def __str__(self):
        return "我的名字是%s我的体重是%.2f"%(self.name,self.weight)
    def run(self):
        print("%s爱跑步"%self.name)
        self.weight-=0.5
    def eat(self):
        print("%s是吃货"%self.name)
        self.weight+=1
xm=Person("小明",75.0)
xm.run()
xm.eat()
print(xm)

 

Published 137 original articles · won praise 3 · Views 4833

Guess you like

Origin blog.csdn.net/qq_38054511/article/details/104607083