创建Dog 类
方法__init__(),Python 自动调用,约定!!!
#创建Dog 类
class Dog:def __init__(self, name, age):self.name = nameself.age = agedef sit(self):print(f"{self.name} is now sitting.")def roll_over(self):print(f"{self.name} rolled over.")#根据类创建实例
my_dog = Dog('Willie', 6)#访问属性
print(f"My dog's name is {my_dog.name}")#调用方法
my_dog.sit()
使用类和实例
class Car(object):"""docstring for Car"""def __init__(self, make, model, year):self.make = makeself.model = modelself.year = year#给属性指定默认值self.odometer_reading = 0def 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):self.odometer_reading = mileagemy_car = Car('audi', 'a4', 2019)
print(my_car.get_descriptive_name())##直接修改属性值
my_car.odometer_reading = 55
my_car.read_odometer()##通过方法修改属性的值
my_car.update_odometer(66)
my_car.read_odometer()
继承
class Car(object):"""docstring for Car"""def __init__(self, make, model, year):self.make = makeself.model = modelself.year = year#给属性指定默认值self.odometer_reading = 0def 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):self.odometer_reading = mileagedef fill_gas_tank(self, volume):self.volume = volumeclass ElectricCar(Car):"""docstring fos ElectricCar"""def __init__(self, make, model, year, battery_size=75):#初始化父类的属性super().__init__(make, model, year)#子类定义属性self.battery_size = battery_size#子类定义方法 def describe_battery(self):print(f"This car has a {self.battery_size}-kWh battery.")#覆盖父类方法def fill_gas_tank(self, volume):print("This car does't need a gas tank.")my_tesla = ElectricCar('tesla', 'model s', '2019')
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
my_tesla.fill_gas_tank(50)
导入类
#导入类
from car import Car, ElectricCarmy_beetle = Car('volkswagen', 'beetle', 2019)
my_tesla = ElectricCar('tesla', 'roadster', 2020)#导入模块
import car
my_beetle = car.Car('volkswagen', 'beetle', 2019)