python学习之路八--类
类名应该用驼峰命名法
面向对象编程是最有效的软件编写方法之一
根据类来创建对象被称为实例化
1.创建类和实用类
class Car:
def __init__(self, name, color):
self.name = name
self.color = color
def drive(self):
print(str(self.color) + " " + str(self.name) + " is already driving")
def get_car_color(self):
return self.color
def get_car_name(self):
return self.name
car = Car("dongfeng","blue") car.drive()
其中方法_init_()每当你根据Car类创建新实例时,Python都会运行它,相当于java中的构造方法
方法_init_()定义成了包含三个形参:self、name、color,形参self并不可少,还必须位于其他形参的前面
2.给属性设定默认值
class Battery(): def __init__(self, battery_size=70): self.battery_size = battery_size def describe_battery(self): print('this car has a '+str(self.battery_size)+'-kwh battery') def get_range(self): if self.battery_size == 70: range = 240 elif self.battery_size == 85: range = 270 message = "this car can go approximately" + str(range) message += "miles on a full charge" print(message)
其中battery_size=70 就是给他设定了默认值3.修改属性值
直接修改属性的值
my_car = Car("a4","red") my_car.color = "blue"
4.通过方法修改属性在类中编写修改属性的方法来修改属性
def change_color(self, color): self.color = color
car.change_color("blue")
5.继承
一个类继承另一个类,他将自动的获得另一个类的所有属性和方法,原有的类为父类,而新类称为子类
from bean.car import Car from bean.battery import Battery class ElecticCar(Car): def __init__(self, name, color): super().__init__(name, color) self.battery = Battery()
⭐️其中一定要注意super()后面跟上小括号 否则会报错TypeError: descriptor '__init__' requires a 'super' object but received a 'str'
重写父类的方法
def drive(self): print("zilei.function" + str(self.color) + " " + str(self.name) + " is already driving")
python标准库
全英文 有例子 有助于学习 也有英文书 当时到今年六月二号亚马逊有卖
https://www.amazon.cn/s/ref=nb_sb_ss_rsis_1_0?__mk_zh_CN=%E4%BA%9A%E9%A9%AC%E9%80%8A%E7%BD%91%E7%AB%99&url=search-alias%3Dstripbooks&field-keywords=python+3+standard+library&sprefix=%2Caps%2C317