创建一个Class和实例

  1. # 创建对象
  2. class Dog:
  3. """A simple attempt to model a dog."""
  4. def __init__(self, name, age):
  5. """Initialize name and age attributes."""
  6. self.name = name
  7. self.age = age
  8. self.color = 'black'
  9. def sit(self):
  10. """Simulate a dog sitting in response to a command."""
  11. print(f"{self.name} is now sitting.")
  12. def roll_over(self):
  13. """Simulate rolling over in response to a command."""
  14. print(f"{self.name} rolled over!")
  15. """可以像JS一样用等号声明"""
  16. a = 'helo'
  17. def test(self):
  18. print(self.a)
  19. # 创建实例
  20. my_dog = Dog('Willie', 6)
  21. print(f"My dog's name is {my_dog.name}.")
  22. print(f"My dog is {my_dog.age} years old.")
  • Class名首字母要大写
  • Class内的函数叫methods
  • init函数必须有2个下划线
  • self是对实例自身的引用

Inheritance

  1. class Car:
  2. """A simple attempt to represent a car."""
  3. def __init__(self, make, model, year):
  4. self.make = make
  5. self.model = model
  6. self.year = year
  7. self.odometer_reading = 0
  8. def get_descriptive_name(self):
  9. long_name = f"{self.year} {self.make} {self.model}"
  10. return long_name.title()
  11. def read_odometer(self):
  12. print(f"This car has {self.odometer_reading} miles on it.")
  13. def update_odometer(self, mileage):
  14. if mileage >= self.odometer_reading:
  15. self.odometer_reading = mileage
  16. else:
  17. print("You can't roll back an odometer!")
  18. def increment_odomenter(self, miles):
  19. self.odometer_reading += miles
  20. class Battery:
  21. """A Simple attempt to model a battery for an electric car."""
  22. def __init__(self, battery_size=75):
  23. """Initialize the battery's attributes."""
  24. self.battery_size = battery_size
  25. def describe_battery(self):
  26. """Print a statement describing the battery size."""
  27. print(f"This car has a {self.battery_size}-kWh battery.")
  28. # 继承
  29. class ElectricCar(Car):
  30. """Reresent aspects of a car, specific to electric vehicles."""
  31. def __init__(self, make, model, year):
  32. """Initialize attributes of the parent class."""
  33. super().__init__(make, model,year) # 继承父class属性
  34. self.battery = Battery() # instance as attribute
  35. # override重写父元素方法
  36. def fill_gas_tank(self):
  37. """Electric cars don't have gas tanks."""
  38. print("This car doesn't need a gas tank!")
  39. my_tesla = ElectricCar('tesla', 'model s', 2019)
  40. print(my_tesla.get_descriptive_name())
  41. my_tesla.battery.describe_battery() # 调用属性上的方法
  42. my_tesla.fill_gas_tank()

Importing Classes

导入多个class

  1. from car import Car, ElectricCar
  2. my_beetle = Car('volkswagen', 'beetle', 2019)
  3. print(my_beetle.get_descriptive_name())
  4. my_tesla = ElectricCar('tesla', 'roadster', 2019)
  5. print(my_tesla.get_descriptive_name())

导入整个module

  1. import car
  2. my_beetle = car.Car('volkswagen', 'beetle', 2019)
  3. print(my_beetle.get_descriptive_name())
  4. my_tesla = car.ElectricCar('tesla', 'roadster', 2019)
  5. print(my_tesla.get_descriptive_name())

不推荐下列导入方式

  1. from module_name import *

在module中导入module

  1. from car import Car
  2. class Battery:
  3. --snip--
  4. class ElectricCar(Car):
  5. --snip--

使用别名

  1. 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

  1. from random import randint
  2. from random import choice
  3. print(randint(1, 6)) # 产生一个[1,6]区间的数
  4. players = ['charles', 'martina', 'michael', 'florence', 'eli']
  5. first_up = choice(players) # 返回list或tuple中的任意一个元素
  6. print(first_up)

https://pymotw.com/3/

Styling Classes

  • class名用驼峰式CamelCase且首字母大写,instance和module名用小写字母和下划线
  • class和module都应该有docstring描述
  • 先import标准库,空一行,再import你自己写的module