创建一个Class和实例
# 创建对象class Dog:"""A simple attempt to model a dog."""def __init__(self, name, age):"""Initialize name and age attributes."""self.name = nameself.age = ageself.color = 'black'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!")"""可以像JS一样用等号声明"""a = 'helo'def test(self):print(self.a)# 创建实例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.")
- Class名首字母要大写
 - Class内的函数叫methods
 - init函数必须有2个下划线
 - self是对实例自身的引用
 
Inheritance
class Car:"""A simple attempt to represent a car."""def __init__(self, make, model, year):self.make = makeself.model = modelself.year = yearself.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):if mileage >= self.odometer_reading:self.odometer_reading = mileageelse:print("You can't roll back an odometer!")def increment_odomenter(self, miles):self.odometer_reading += milesclass Battery:"""A Simple attempt to model a battery for an electric car."""def __init__(self, battery_size=75):"""Initialize the battery's attributes."""self.battery_size = battery_sizedef describe_battery(self):"""Print a statement describing the battery size."""print(f"This car has a {self.battery_size}-kWh battery.")# 继承class ElectricCar(Car):"""Reresent 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) # 继承父class属性self.battery = Battery() # instance as attribute# override重写父元素方法def fill_gas_tank(self):"""Electric cars don't have gas tanks."""print("This car doesn't need a gas tank!")my_tesla = ElectricCar('tesla', 'model s', 2019)print(my_tesla.get_descriptive_name())my_tesla.battery.describe_battery() # 调用属性上的方法my_tesla.fill_gas_tank()
Importing Classes
导入多个class
from car import Car, ElectricCarmy_beetle = Car('volkswagen', 'beetle', 2019)print(my_beetle.get_descriptive_name())my_tesla = ElectricCar('tesla', 'roadster', 2019)print(my_tesla.get_descriptive_name())
导入整个module
import carmy_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())
不推荐下列导入方式
from module_name import *
在module中导入module
from car import Carclass Battery:--snip--class ElectricCar(Car):--snip--
使用别名
from electric_car import ElectricCar as EC
Keep your code structure simple. Try doing everything in one file and moving your classes to separate modules.
The Python Standard Library
from random import randintfrom random import choiceprint(randint(1, 6)) # 产生一个[1,6]区间的数players = ['charles', 'martina', 'michael', 'florence', 'eli']first_up = choice(players) # 返回list或tuple中的任意一个元素print(first_up)
Styling Classes
- class名用驼峰式CamelCase且首字母大写,instance和module名用小写字母和下划线
 - class和module都应该有docstring描述
 - 先import标准库,空一行,再import你自己写的module
 
