类和对象
类是对象的模板, 对象是类的实例
类创建对象被称为实例化。
类的定义
面向对象的类中只有属性和方法(函数)
class 类名():
# TODO 属性
def 方法1(self, 参数列表):
pass
def 方法2(self, 参数列表):
pass
创建对象
对象名 = 类名()
自定义 : 小猫 爱 吃 鱼,小猫 要 喝 水。
# 类名 大驼峰 (单词首字母都大写)
class Cat():
def eat(self):
print("小猫爱吃鱼")
def drink(self):
print("小猫爱喝水")
# 使用类
cat1 = Cat()
# 调用方法
cat1.eat()
cat1.drink()
class Car():
def drive(self):
print("开车")
def destory(self):
print("报废车")
car1=Car()
car1.drive()
car1.destory()
def haha():
print("haha")
属性的定义
初阶定义
class Cat():
name = None
color = None
def eat(self):
print("小猫爱吃鱼")
def drink(self):
print("小猫爱喝水")
c1 = Cat()
print(c1.name)
c1.name = "豆豆"
c1.color = 'white'
print(c1.name)
print(c1.color)
c2 = Cat()
# c2.name = "豆花"
c2.name = "豆豆"
c2.color = 'white'
print(c2.name)
# 区分是两个不同的对象
print(id(c1))
print(id(c2))
self的含义
class Cat():
def __init__(self):
"""构造方法:类被实例化的时候会自动调用"""
print("__init__被调用")
self.name = "豆豆"
def eat(self):
print("self 的地址是 {}".format(id(self)))
print("小猫爱吃鱼")
def drink(self):
print("小猫爱喝水")
# Cat() 匿名对象
# self : 代表当前类对象
cat1 = Cat()
print("cat1 id = ", id(cat1))
cat1.eat()
cat2 = Cat()
print("cat2 id = ", id(cat2))
cat2.eat()
有参构造函数
class Cat():
def __init__(self, name, color, age=1):
"""构造方法:类被实例化的时候会自动调用"""
self.name = name
self.color = color
self.age=age
def eat(self):
print("self 的地址是 {}".format(id(self)))
print("小猫爱吃鱼")
def drink(self):
print("小猫爱喝水")
c1 = Cat("豆豆", "black")
c2 = Cat("豆花", "white")
c3 = Cat("花卷", "white", 5)
c4 = Cat()
print(c1.name)
print(c2.name)
print(c2.age)
print(c3.age)
str
class Cat():
def __init__(self, name, color, age=1):
"""构造方法:类被实例化的时候会自动调用"""
self.name = name
self.color = color
self.age=age
def eat(self):
print("self 的地址是 {}".format(id(self)))
print("小猫爱吃鱼")
def drink(self):
print("小猫爱喝水")
def __str__(self):
return "小猫名字是:{}, " \
"颜色: {} age = {}".format(self.name, self.color, self.age)
c1 = Cat("豆豆", "black")
c2 = Cat("豆花", "white")
print(c1)
print(c2)
面向对象vs 面向过程
# 面向过程
def carInfo(brand, price):
print("the car's brand is {}, price = {}".format(brand, price))
print("面向过程")
carInfo("passat", 250000)
carInfo("audi", 250000)
# 面向对象
class Car():
def __init__(self,brand,price):
self.brand=brand
self.price=price
def __str__(self):
return"汽车品牌是:{}价格:{}".format(self.brand,self.price)
c1=Car("passat",250000)
print(c1)
c2=Car("audi",250000)
print(c2)
新需求—加一个行驶里程显示的功能
# 面向过程
def carInfo(brand, price):
print("the car's brand is {}, price = {}".format(brand, price))
def showDistance(oldDistance, distance):
return oldDistance + distance
print("面向过程")
carInfo("passat", 250000)
carInfo("audi", 250000)
print(showDistance(200, 300))
# 面向对象
class Car():
def __init__(self,brand,price):
self.brand=brand
self.price=price
self.distance = 0
def __str__(self):
return"汽车品牌是:{}价格:{}".format(self.brand,self.price)
def showDistance(self, distance):
return self.distance + distance
c1=Car("passat",250000)
print(c1)
print(c1.showDistance(5000))
print(c1.showDistance(300))
c2=Car("audi",250000)
print(c2)