Python中构造函数init与类的实例化
第一个例子:
- class叫类名,名称叫Employee。
假设Employee是一个招聘系统
- __init__叫类的初始化方法,名字是固定不能变的。
招聘的具体要求,比如需要的语言language,经验experience,薪水salary
- self.language指的是招聘系统里自己写的要求(即language)
= language指的是用这个系统的人给出的语言(即李华说的Python)
其他同理
- LiHua = Employee("Python","5",5000)
来了个叫做李华的人,给出了自己的条件,会用的语言language是Pyhon,工作经验experience是5年,薪水salary要求给5000
类的实例就是LiHua,感觉实例就是实际例子,初始化方法就是提前说我的要求,实例化就是真来了个人,说我达到了哪些要求
class Employee: def __init__(self,language,experience,salary): self.language = language self.experience = experience self.salary = salary LiHua = Employee("Python","5",5000) print(LiHua.language)第二个例子:
Phone是设计图纸(定义了手机该有的样子)phone1、phone2、phone3是三台真实的手机(三个不同的实例)每个实例都有自己的颜色、品牌、价格(互不干扰)
class Phone: """手机设计图纸""" def __init__(self, brand, color, price): self.brand = brand # 品牌 self.color = color # 颜色 self.price = price # 价格 def call(self, number): print(f"{self.color}色的{self.brand}手机正在拨打{number}") def info(self): print(f"{self.brand} {self.color} 售价:{self.price}元") # ========== 实例化:根据图纸造出真实手机 ========== phone1 = Phone("华为", "黑色", 5999) # 造一台华为 phone2 = Phone("苹果", "白色", 6999) # 造一台苹果 phone3 = Phone("小米", "蓝色", 3999) # 造一台小米 # 使用实例 phone1.call("13800138000") # 黑色色的华为手机正在拨打13800138000 phone2.info() # 苹果 白色 售价:6999元 phone3.call("10086") # 蓝色的小米手机正在拨打10086