P9-类
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 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!") my_dog = Dog('Willie', 6) your_dog = Dog('Lucy', 3) print(f"My dog's name is {my_dog.name}.") print(f"My dog is {my_dog.age} years old.") my_dog.sit() print(f"\nYour dog's name is {your_dog.name}.") print(f"Your dog is {your_dog.age} years old.") your_dog.sit()
class 定义一个类 _init_(self,xxx,xxxx) _init_ 构造方法 构造方法的self不用传 自动传入,相当于Java的this指向实例的本身
self中的属性就是类的属性
class Car: """A simple attempt to represent a car.""" def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): long_name = f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): print(f"This car has {self.odometer_reading} miles on it.") def update_odometer(self, mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, miles): self.odometer_reading += miles 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 = 75 def describe_battery(self): """Print a statement describing the battery size.""" print(f"This car has a {self.battery_size}-kWh battery.") my_tesla = ElectricCar('tesla', 'model s', 2019) print(my_tesla.get_descriptive_name()) my_tesla.describe_battery()
子类和父类必须在同一个文件中,且位于子类前面
在子类的 _init_中调用super()
from car import Car my_new_car = Car('audi', 'a4', 2019) print(my_new_car.get_descriptive_name()) my_new_car.odometer_reading = 23 my_new_car.read_odometer()
导入类
import car my_beetle = car.Car('volkswagen', 'beetle', 2019) print(my_beetle.get_descriptive_name()) my_tesla = car.ElectricCar('tesla', 'roadster', 2019) print(my_tesla.get_descriptive_name())
导入整个模块