Python–面相对象基础
1.面相对象基础概念
面相过程编程vs面相对象编程
2.类与对象
类:是描述一组具有相同属性和方法的模版
对象:对象是类的实例,是基于类创建出来的
对象是由类创建出来的,创建对象的过程,也称为对象的实例化,类名的命名规范,遵循大驼峰命名法,每个单词的首字母都是大写,单词之间没有分隔符,例如:UserInfo UserAccount
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Car: pass
c1 = Car() c1.color = "red" c1.brand = "BMW" c1.name = "X5" c1.price = 500000
print(c1.__dict__)
class Car: def __init__(self, color, brand, name, price): self.color = color self.brand = brand self.name = name self.price = price print("Car is created")
c2 = Car("blue", "Audi", "A4", 400000) print(c2.__dict__)
print("--------------------------------")
|
__init__:初始化方法,对象创建后自动调用,主要用于设置对象的初始状态(设置对象属性)
3.实例方法
在类中定义实例方法时,定义语法与之前学习的函数定义的方式是一致的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class Car: def __init__(self, color, brand, name, price): self.color = color self.brand = brand self.name = name self.price = price print("Car is created")
def running(self): print(f"{self.brand} {self.name} is running")
def total_cost(self, discount, rate): """ 计算总费用 参数: discount:折扣率 rate:月利率 返回值: 总费用 """ total_cost = self.price * discount + rate * self.price return total_cost
c3 = Car("red", "Audi", "A4", 400000) c3.running() print(c3.total_cost(0.9, 0.03)) print("--------------------------------")
|
4.魔法方法
魔法方法是指Pyton中提供的以下划线开头和结尾的特殊方法,用于定义类的特殊行为。比如:__init__,魔法方法是不需要我们手动嗲用的,Python会在合适的时机自动调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| class Car: def __init__(self, color, brand, name, price): self.color = color self.brand = brand self.name = name self.price = price print("Car is created")
def running(self): print(f"{self.brand} {self.name} is running") def __str__(self): return f"{self.brand} {self.name} is a {self.color} car" def __eq__(self, other): return self.brand == other.brand and self.name == other.name
def __lt__(self, other): return self.price < other.price
def __gt__(self, other): return self.price > other.price def __le__(self, other): return self.price <= other.price def __ge__(self, other): return self.price >= other.price c1=Car("red", "Audi", "A4", 400000) c2=Car("blue", "Audi", "A4", 400000) c3=Car("red", "Audi", "A4", 400000)
print(c1 == c2) print(c1 == c3) print(c1 < c2) print(c1 > c2) print(c1 <= c2) print(c1 >= c2) print("--------------------------------")
|
5.实例属性与类属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Car: wheel = 4 tax_rate = 0.03 def __init__(self, color, brand, name, price): self.color = color self.brand = brand self.name = name self.price = price self.wheel = 2 print("Car is created")
def total_cost(self, discount, rate): """ 计算总费用 参数: discount:折扣率 rate:月利率 返回值: 总费用 """ total_cost = self.price * discount + rate * self.price return total_cost c1 = Car("red", "Audi", "A4", 400000) print(c1.wheel) print(c1.tax_rate) print(c1.__dict__) print("--------------------------------")
|