一、类的基础操作

1. 创建和使用类:

  1. # 首先我们先创建一个名为 Dog 的类(python中首字母大写的名字为类名)
  2. class Dog():
  3. """A simple attempt to model a dog.""" # 文档字符串注释
  4. # _init_()方法比较特殊,创建新实例时会自动运行 (def后面的名为“方法”)
  5. # 在方法定义中self形参必不可少,python会自动传入self实参,我们不用管
  6. def __init__(self, name, age):
  7. """Initialize name and age attributes."""
  8. self.name = name # 以self为前缀的变量可供类中的所有方法使用
  9. self.age = age
  10. def sit(self):
  11. """Simulate a dog sitting in response to a command."""
  12. print(self.name.title() + " is now sitting.")
  13. def roll_over(self):
  14. """Simulate rolling over in response to a command."""
  15. print(self.name.title() + " rolled over!")
  16. # 创建两个实例
  17. my_dog = Dog('willie', 6)
  18. your_dog = Dog('lucy', 3)
  19. # 用 句点法 访问属性
  20. print("My dog's name is " + my_dog.name.title() + ".")
  21. print("My dog is " + str(my_dog.age) + " years old.") # 注意将数字转化为字符串!
  22. my_dog.sit()
  23. print("\nYour dog's name is " + your_dog.name.title() + ".")
  24. print("Your dog is " + str(your_dog.age) + " years old.")
  25. your_dog.sit()

:::tips output:
My dog’s name is Willie.
My dog is 6 years old.
Willie is now sitting.

Your dog’s name is Lucy.
Your dog is 3 years old.
Lucy is now sitting. :::

2. 给属性指定、修改默认值:

  1. """A class that can be used to represent a car."""
  2. class Car():
  3. """A simple attempt to represent a car."""
  4. def __init__(self, manufacturer, model, year):
  5. """Initialize attributes to describe a car."""
  6. self.manufacturer = manufacturer
  7. self.model = model
  8. self.year = year
  9. self.odometer_reading = 0
  10. # 👆类中的每个属性都必须有初始值。在方法_init__()内指定初始值后就无需包含为
  11. # (接上句)它提供初始值的形参。
  12. def get_descriptive_name(self):
  13. """Return a neatly formatted descriptive name."""
  14. long_name = str(self.year) + ' ' + self.manufacturer + ' ' + self.model
  15. return long_name.title()
  16. def read_odometer(self):
  17. """Print a statement showing the car's mileage."""
  18. print("This car has " + str(self.odometer_reading) + " miles on it.")
  19. def update_odometer(self, mileage):
  20. """
  21. Set the odometer reading to the given value.
  22. Reject the change if it attempts to roll the odometer back.
  23. """
  24. if mileage >= self.odometer_reading:
  25. self.odometer_reading = mileage
  26. else:
  27. print("You can't roll back an odometer!")
  28. def increment_odometer(self, miles):
  29. """Add the given amount to the odometer reading."""
  30. self.odometer_reading += miles
  1. my_used_car = Car('五菱宏光','至尊顶配','1999')
  2. print(my_used_car.get_descriptive_name())
  3. my_used_car.update_odometer(23500)
  4. my_used_car.read_odometer()
  5. my_used_car.increment_odometer(100)
  6. my_used_car.read_odometer()

:::tips output:
1999 五菱宏光 至尊顶配
This car has 23500 miles on it.
This car has 23600 miles on it. :::


二、继承

1. 关于子类

  1. """A set of classes that can be used to represent electric cars."""
  2. # 引用Car类
  3. from car import Car
  4. class Battery():
  5. """A simple attempt to model a battery for an electric car."""
  6. def __init__(self, battery_size=60):
  7. """Initialize the batteery's attributes."""
  8. self.battery_size = battery_size
  9. def describe_battery(self):
  10. """Print a statement describing the battery size."""
  11. print("This car has a " + str(self.battery_size) + "-kWh battery.")
  12. def get_range(self):
  13. """Print a statement about the range this battery provides."""
  14. if self.battery_size == 60:
  15. range = 140
  16. elif self.battery_size == 85:
  17. range = 185
  18. message = "This car can go approximately " + str(range)
  19. message += " miles on a full charge."
  20. print(message)
  21. #Car类的子类
  22. class ElectricCar(Car):
  23. """Models aspects of a car, specific to electric vehicles."""
  24. def __init__(self, manufacturer, model, year):
  25. """
  26. 初始化父类的属性👆,在初始化电动汽车特有的属性👇
  27. """
  28. super().__init__(manufacturer, model, year)
  29. self.battery = Battery() #batter变量使用Battery类
  30. # 如果想重写父类的方法,def一个同名方法即可。

2. 导入类:

1.from (文件名) import (类名)
2.import (文件名) 导入整个模块(这样做不怕重名,因为要用句点法访问)
3.from (文件名) import *导入模块中的所有类(不推荐使用,有可能会重名)

3. Python标准库:

这里只做简单介绍,如collections模块中的OrderedDict类,它相当于一个有序的字典。

  1. from collections import OrderedDict
  2. favorite_languages = OrderedDict()
  3. favorite_languages['jen'] = 'python'
  4. favorite_languages['sarah'] = 'c'
  5. favorite_languages['edward'] = 'ruby'
  6. favorite_languages['phil'] = 'python'
  7. for name, language in favorite_languages.items():
  8. print(name.title() + "'s favorite language is " +
  9. language.title() + ".")

:::tips output:
Jen’s favorite language is Python.
Sarah’s favorite language is C.
Edward’s favorite language is Ruby.
Phil’s favorite language is Python.
(是有序的) :::

4. 类编码风格(驼峰命名法):

  • 类名中的每个单词首字母都大写,而使用下划线;
  • 实例名和模块名都采用小写格式,并在每个单词之间采用下划线
  • 每个类、模块定义后面紧跟一个文档字符串注释;