5200.9 Class
类为所有的对象提供通用的行为,每个对象拥有各自独特的属性,这种面向对象能有效地模拟现实世界。
创建类
class Dog:
"""A simple attempt to model a dog."""
def __init__(self, name, age):
"""Initialize name and age attributes."""
self.name = name
self.age = age
self.odometer_reading = 0
def sit(self):
"""Simulate a dog sitting in response to a command."""
print(f"{self.name} is now sitting.")
def roll_over(self):
"""Simulate rolling over in response to a command."""
print(f"{self.name} rolled over!")通过类生成实例
class Dog:
--snip--
my_dog = Dog('Willie', 6)
print(f"My dog's name is {my_dog.name}.")
print(f"My dog is {my_dog.age} years old.")当类被实例化的时候,__init__() 会自动执行。
方法定义中必须要包含self参数,这个参数要置于其他参数之前。
在init方法中,被self定义的variable可以被任何实例访问。
通过dot notation调用属性和方法
print(f"My dog's name is {my_dog.name}.")
print(f"My dog is {my_dog.age} years old.")
my_dog.sit()修改属性
python 提供了三种修改属性的方法:
- 通过属性直接访问
- 通过方法在内部修改 attribute
- 有时候需要给 attributes增加值,而不是修改值。
继承
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""Initialize attributes of the parent class."""
super().__init__(make, model, year)集成的方法,需要通过super().__init__(make, model, year) 去掉用父类的方法。这样子类就可以调用父类的所有属性和方法。
为子类创建独有的方法和属性
class Car:
--snip--
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""
Initialize attributes of the parent class.
Then initialize attributes specific to an electric car.
"""
super().__init__(make, model, year)
self.battery_size = 40
上面的例子中,self.battery_size 就是自己定义的属性。
模块化
也可以把一些相关的方法放到一个文件中,这样就可以避免文件冗长。 模块化的方法可以让主程序干净整洁,只在高的层级去关注主程序。
import
基础语法
from car import Car, ElectricCar导入完整模块
import car导入所有的class(不推荐)
from module_name import *别名
使用别名
from electric_car import ElectricCar as ECmy_leaf = EC('nissan', 'leaf', 2024)import electric_car as ec
my_leaf = ec.ElectricCar('nissan', 'leaf', 2024)