一、类的基础操作
1. 创建和使用类:
# 首先我们先创建一个名为 Dog 的类(python中首字母大写的名字为类名)
class Dog():
"""A simple attempt to model a dog.""" # 文档字符串注释
# _init_()方法比较特殊,创建新实例时会自动运行 (def后面的名为“方法”)
# 在方法定义中self形参必不可少,python会自动传入self实参,我们不用管
def __init__(self, name, age):
"""Initialize name and age attributes."""
self.name = name # 以self为前缀的变量可供类中的所有方法使用
self.age = age
def sit(self):
"""Simulate a dog sitting in response to a command."""
print(self.name.title() + " is now sitting.")
def roll_over(self):
"""Simulate rolling over in response to a command."""
print(self.name.title() + " rolled over!")
# 创建两个实例
my_dog = Dog('willie', 6)
your_dog = Dog('lucy', 3)
# 用 句点法 访问属性
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.") # 注意将数字转化为字符串!
my_dog.sit()
print("\nYour dog's name is " + your_dog.name.title() + ".")
print("Your dog is " + str(your_dog.age) + " years old.")
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. 给属性指定、修改默认值:
"""A class that can be used to represent a car."""
class Car():
"""A simple attempt to represent a car."""
def __init__(self, manufacturer, model, year):
"""Initialize attributes to describe a car."""
self.manufacturer = manufacturer
self.model = model
self.year = year
self.odometer_reading = 0
# 👆类中的每个属性都必须有初始值。在方法_init__()内指定初始值后就无需包含为
# (接上句)它提供初始值的形参。
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = str(self.year) + ' ' + self.manufacturer + ' ' + self.model
return long_name.title()
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value.
Reject the change if it attempts to roll the odometer back.
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
"""Add the given amount to the odometer reading."""
self.odometer_reading += miles
my_used_car = Car('五菱宏光','至尊顶配','1999')
print(my_used_car.get_descriptive_name())
my_used_car.update_odometer(23500)
my_used_car.read_odometer()
my_used_car.increment_odometer(100)
my_used_car.read_odometer()
:::tips
output:
1999 五菱宏光 至尊顶配
This car has 23500 miles on it.
This car has 23600 miles on it.
:::
二、继承
1. 关于子类
"""A set of classes that can be used to represent electric cars."""
# 引用Car类
from car import Car
class Battery():
"""A simple attempt to model a battery for an electric car."""
def __init__(self, battery_size=60):
"""Initialize the batteery's attributes."""
self.battery_size = battery_size
def describe_battery(self):
"""Print a statement describing the battery size."""
print("This car has a " + str(self.battery_size) + "-kWh battery.")
def get_range(self):
"""Print a statement about the range this battery provides."""
if self.battery_size == 60:
range = 140
elif self.battery_size == 85:
range = 185
message = "This car can go approximately " + str(range)
message += " miles on a full charge."
print(message)
#Car类的子类
class ElectricCar(Car):
"""Models aspects of a car, specific to electric vehicles."""
def __init__(self, manufacturer, model, year):
"""
初始化父类的属性👆,在初始化电动汽车特有的属性👇
"""
super().__init__(manufacturer, model, year)
self.battery = Battery() #batter变量使用Battery类
# 如果想重写父类的方法,def一个同名方法即可。
2. 导入类:
1.from (文件名) import (类名)
2.import (文件名)
导入整个模块(这样做不怕重名,因为要用句点法访问)
3.from (文件名) import *
导入模块中的所有类(不推荐使用,有可能会重名)
3. Python标准库:
这里只做简单介绍,如collections模块中的OrderedDict类,它相当于一个有序的字典。
from collections import OrderedDict
favorite_languages = OrderedDict()
favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " +
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. 类编码风格(驼峰命名法):
- 类名中的每个单词首字母都大写,而不使用下划线;
- 实例名和模块名都采用小写格式,并在每个单词之间采用下划线;
- 每个类、模块定义后面紧跟一个文档字符串注释;