导图社区 Python学习笔记
python 学习笔记,对常规的入门知识进行整理,可帮助快速入门,有需要的同学可以收藏下哟。
编辑于2022-08-10 21:13:03python
基础
入门
print()
打印在终端
pirnt(value, ..., sep=" ", end="\n")
value: 打印的数据
sep: 数据间默认用空格作为分隔符
end: 打印完成后默认换行
print("hello")
打印字符串
print(100)
打印数字
print(3*2+1)
打印计算式
print(1>2)
打印条件语句
input()
比较运算符
==
比较对象是否相等
!=
比较对象是否不相等
x>y
返回x是否大于y
x<y
返回x是否小于y
x>=y
返回x是否大于等于y
x<=y
返回x是否小于等于y
逻辑运算符
and
“与”如x为False,x and y返回False,否则返回y的计算值
or
“或”如x是True,返回True,否则返回y的计算值
not
“非”如x是True返回False。如x是False返回True
数学运算
sum(*iter)
求和
min(*iter)
最小值
max(*iter)
最大值
abs(*num)
绝对值
round(x, [d])
四舍五入,d是保留小数位数
compllex(a, [b])
创建复数
编码
bin(*num)
查看数字的二进制编码
oct(*num)
查看数字的八进制编码
hex(*num)
查看数字的十六进制编码
ord(*char)
查看字符的ARSIC编码
函数
len(*obj)
查看对象的长度
dir(func)
查看对象的方法
type(*obj)
查看对象类型
cmp(x, y)
比较两个对象的大小,返回-1. 0, 1
bytes(*num)
查看对象的字节数
map(func, *iter)
根据提供的函数对指定序列映射
enumerate(*iter)
带有索引的序列,一般和for循环共同使用
nums = ['one', 'two', 'three'] for i, num in enumerate(nums): print(i, num)
eval(*source)
执行字符串表达式
num = eval("3*7") print(num)
filter(func, *iter)
过滤掉不符合条件的元素,返回由符合条件元素组成的新列表
def is_odd(n): return n % 2 == 1 newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) print(newlist)
字符串str
由字符、数字等组成的一段文本,具有顺序性、不可更改性等
s = "abcd" for i in s: print(i)
索引和切片
索引
s[num]
正向索引从0开始,逆向索引从-1开始
>>> s = "abc" >>> s[0] 'a' >>> s[-1] 'c'
切片
s[start: end: step]
切片,从字符串中抽取一个片段,开始、结束、步长均可省略
>>> s = "abc" >>> s[0: 3: 2] 'ac'
s[start: ]
抽出从start位置到最后的片段
>>> s = "abc" >>> s[1:] 'bc'
s[: end]
抽出从0到end位置的片段
>>> s = "abc" >>> s[: 2] 'ab' >>> s[: -1] 'ab'
s[ : ]
显示整个字符串
>>> s = "abc" >>> s[ : ] 'abc'
属性与方法
capitalize()
将字符串的首字母转换为大写
>>> s = "abc" >>> s.capitalize() 'Abc'
title()
将字符串的首字母转换为大写
casefold()
将字符串中的字母转换为小写
>>> s = "Abc" >>> s.casefold() 'abc'
upper()
将字符串中的字符全部转换为大写
>>> line = "aaa, bbb, ccc, ddd" >>> line.upper() 'AAA, BBB, CCC, DDD'
lower()
将字符串中的字符全部转为小写
>>> s = "ABC" >>> s.lower() 'abc'
isalpha()
判断字符串是否全部由字母组成,是返回True,否返回False
>>> line = "aaa, bbb, ccc, ddd" >>> line.isalpha() False
isdigit()
判断字符串是否全部由数字组成,,是返回True,否返回False
>>> s = "abcd123" >>> s.isalnum() False
isalnum()
判断字符串是否全部由数字和字符组成,是返回True,否返回False
>>> s = "abcd123" >>> s.isalnum() True
istitle()
判断字符串的首字母是否为大写,是返回True,否返回False
>>> s = "Abc" >>> s.istitle() True
isupper()
判断字符串是否全部为大写,是返回True,否返回False
>>> s = "Abc" >>> s.isupper() False
islower()
判断字符串中的字母是否全部都是小写,是返回True,否返回False
>>> s = "abcd123" >>> s.islower() True
split(sep=None)
将字符串以分隔符进行拆分
>>> line = "aaa, bbb, ccc, ddd" >>> line.split(",") ['aaa', ' bbb', ' ccc', ' ddd']
replace(old, new)
查找并替换字符串中的片段
>>> s = "spam" >>> s.replace("pa", "abc") 'sabcm'
count(sub[, start[, end]])
计算字符串中某个字符出现的数量
>>> s = "abcd" >>> s.count("a") 1
find(sub[, start[, end]])
查找字符片段在字符串中的位置(第一个)
>>> s = "spam" >>> s.find("pa") 1
endswith(suffix[, start[, end]])
判断字符串是否以某个字符结尾,是返回True,否返回False
>>> s = "abcd" >>> s.endwith("d") False
index(sub[, start[, end]])
返回字符串中某个字符第一次出现的下标
>>> s = "abcd" >>> s.index("b") 1
join(iterable, /)
将多个字符串以某个连接符进行连接
>>> "".join(["ab", "cd", "ef"] 'abcdef'
列表list
列表
列表是一个其他对象的集合,通过相对位置来存储的,故存在顺序性
L = ['a', 'c', 'b', 'd'] for i in L: print(i)
索引和切片
同字符串的索引和切片
属性与方法
clear()
清楚列表中的全部内容
>>> L = ["a", "b", "c"] >>> L.clear() >>> L
copy()
复制当前列表
>>> L = ["a", "b", "c"] >>> N = L.copy() >>> N ["a", "b", "c"]
pop()
删除列表中最后一个元素
>>> L = ["a", "b", "c"] >>> L.pop() >>> 'c' >>> L ['a', 'b']
reverse()
将列表中的元素逆序排列
>>> L = ["a", "b", "c"] >>> L.reverse() >>> L ['c', 'b', 'a']
sort()
将列表中的元素升序排列
>>> L = ['a', 'c', 'b'] >>> L.sort() >>> L ['a', 'b', 'c']
append(object)
在列表的最后增加一个对象
>>> L = ['a', 'c', 'b'] >>> L.append('d') >>> L ['a', 'b', 'c', 'd']
extend(iterable)
在列表的最后增加可迭代对象(多个内容)
L = ['a', 'c', 'b', 'a'] >>> L.extend(['d', 'e', 'f']) >>> L ['a', 'c', 'b', 'd', 'e', 'f']
count(object)
计算某个对象在列表中出现的次数
>>> L = ['a', 'c', 'b', 'a'] >>> L.count('a') 2
index(object[, start[, end]])
返回列表中某个对象第一次出现的下标
>>> L = ['a', 'c', 'b', 'a'] >>> L.index('a) 0
insert(index, object)
在某个下标之前插入一个对象
>>> L = ['a', 'c', 'b'] >>> L.insert(0, "s") >>> L ['s', 'a', 'b', 'c']
remove(objcet)
删除列表中特定的对象(第一个)
>>> L = ['a', 'c', 'b', 'a'] >>> L.remove('a') >>> L ['c', 'b', 'a']
字典dict
简介
字典是一个其他对象的集合,但是通过键而不是相对位置来存储的,故没有顺序性
使用字典
创建一个空字典
>>> D = {}
访问字典的值
>>> D = {"color": "green"} >>> print(D["color"]) green
添加键值对
>>> D = {"color": "green"} >>> print(D) {'color': 'green'} >>> D["num"] = 5 >>> print(D) {'color': 'green', 'num': 5}
修改字典的值
>>> D = {'color': 'green', 'num': 5} >>> D['num'] = 7 >>> print(D) {'color': 'green', 'num': 7}
删除键值对
>>> D = {'color': 'green', 'num': 5} >>> del D['num'] >>> print(D) {'color': 'green'}
遍历字典
遍历字典所有的键值对
>>> D = {'color': 'green', 'num': 5} >>> for key, value in D.items(): ... print(key, value) color green num 5
遍历字典中所有的键
>>> D = {'color': 'green', 'num': 5} >>> for key in D.keys(): ... print(key) color num
遍历字典中所有的值
>>> D = {'color': 'green', 'num': 5} >>> for value in D.values(): ... print(value) green 5
字典嵌套
字典列表
>>> A = {'color': 'green', 'points': 5} >>> B = {'color': 'yellow', 'points': 10} >>> C = {'color': 'red', 'points': 15} >>> D = [A, B, C] >>> for item in D: ... print(item) {'color': 'green', 'points': 5} {'color': 'yellow', 'points': 10} {'color': 'red', 'points': 15}
字典中存储列表
things = { 'jen': ['python', 'ruby'], 'sarah': ['c'], 'edward': ['ruby', 'go'], 'phil': ['python', 'haskell'], } for name, languages in things.items(): print("\n" + name.title() + "'s favorite languages are:") for language in languages: print("\t" + language.title())
字典中存储字典
users = { 'aeinstein': { 'first': 'albert', 'last': 'einstein', 'location': 'princeton', }, 'mcurie': { 'first': 'marie', 'last': 'curie', 'location': 'paris', }, } for username, user_info in users.items(): print("\nUsername: " + username) full_name = user_info['first'] + " " + user_info['last'] location = user_info['location'] print("\tFull name: " + full_name.title()) print("\tLocation: " + location.title())
条件判断与循环
if条件判断
单个if判断
num = 10 if num > 5: print("%d > 5" % num)
if-else判断
num = 10 if num > 5: print("%d > 5" % num) else: print("%d < 5" % num)
if-elif-else判断
score = 90 if score > 90: print("%d is A" % score) elif score > 80: print("%d is B" % score) elif score > 700: print("%d is C" % score) elif score > 60: print("%d is D" % score) else: print("%d is E" % score)
for循环
打印字符串/列表内容
STR = "abcdefghijklmn" for iter in STR: print(iter) LIST = ['a', 'b', 'c', 'd'] for iter in LIST: print(iter)
range函数
for iter in range(1, 10): print(iter)
while循环
使用while循环
num = 1 while num <= 5: print(num) num += 1
根据输入退出循环
prompt = "Tell me something(Enter 'quit' to end the program):" message = "" while message != 'quit': message = input(prompt) if message != 'quit': print(message)
使用标志
prompt = "Tell me something(Enter 'quit' to end the program):" message = "" flag = True while flag: message = input(prompt) if message == 'quit': flag = False else: print(message)
使用break退出循环
prompt = "Tell me something(Enter 'quit' to end the program):" message = "" flag = True while flag: message = input(prompt) if message == 'quit': break else: print(message)
在循环中使用continue
num = 0 while num < 10: num += 1 if num % 2 == 0: continue print(num)
while循环处理列表
# 首先,创建一个待验证用户列表 # 和一个用于存储已验证用户的空列表 unconfirmed_users = ['alice', 'brian', 'candace'] confirmed_users = [] # 验证每个用户,直到没有未验证用户为止 # 将每个经过验证的列表都移到已验证用户列表中 while unconfirmed_users: current_user = unconfirmed_users.pop() print("Verifying user: " + current_user.title()) confirmed_users.append(current_user) # 显示所有已验证的用户 print("\nThe following users have been confirmed:") for confirmed_user in confirmed_users: print(confirmed_user.title())
while循环字典存储
responses = {} # 设置一个标志,指出调查是否继续 polling_active = True while polling_active: # 提示输入被调查者的名字和回答 name = input("\nWhat is your name? ") response = input("Which mountain would you like to climb someday? ") # 将答卷存储在字典中 responses[name] = response # 看看是否还有人要参与调查 repeat = input("Would you like to let another person respond? (yes/ no) ") if repeat == 'no': polling_active = False # 调查结束,显示结果 print("\n--- Poll Results ---") for name, response in responses.items(): print(name + " would like to climb " + response + ".")
函数
函数
是带有名字的代码块,用于完成具体的任务
优点:使程序简洁、有利于阅读、可重复调用
定义函数
函数初识
def say_hello(): print("hello!") say_hello()
向函数传递信息
def say_hello(name): print("hello " + name.title() + "!") say_hello('james')
形参和实参
def say_hello(name): #此处name为形参 print("hello " + name.title() + "!") say_hello('james') #此处james为形参
传递实参
位置实参
def describe_pet(animal_type, pet_name): print("I have a " + animal_type.title() + ",", end=" ") print("It's name is " + pet_name.title() + ".") describe_pet("dog", "jully")
关键字实参
def describe_pet(animal_type, pet_name): print("I have a " + animal_type.title() + ",", end=" ") print("It's name is " + pet_name.title() + ".") describe_pet(animal_type="dog", pet_name="jully")
形参默认值
def describe_pet(pet_name, animal_type='dog'): print("I have a " + animal_type.title() + ",", end=" ") print("It's name is " + pet_name.title() + ".") describe_pet("jully")
返回值
返回值初识
def get_formatted_name(first_name, last_name): full_name = first_name + ' ' + last_name return full_name.title() musician = get_formatted_name('jimi', 'hendrix') print(musician)
可选实参
def get_formatted_name(first_name, last_name, middle_name=''): if middle_name: full_name = first_name + ' ' + middle_name + ' ' + last_name else: full_name = first_name + ' ' + last_name return full_name.title() musician = get_formatted_name('jimi', 'hendrix') print(musician) musician = get_formatted_name('john', 'hooker', 'lee') print(musician)
返回字典
def build_person(first_name, last_name): person = {'first': first_name, 'last': last_name} return person musician = build_person('jimi', 'hendrix') print(musician)
函数与while循环结合
def get_formatted_name(first_name, last_name): full_name = first_name + ' ' + last_name return full_name.title() while True: print("\nPlease tell me your name:") print("(enter 'q' at any time to quit)") f_name = input("First name: ") if f_name == 'q': break l_name = input("Last name: ") if l_name == 'q': break formatted_name = get_formatted_name(f_name, l_name) print("\nHello, " + formatted_name + "!")
传递列表
在函数中修改列表
def print_models(unprinted_designs, completed_models): while unprinted_designs: current_design = unprinted_designs.pop() print("Printing model: " + current_design) completed_models.append(current_design) def show_completed_models(completed_models): print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_model) unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron'] completed_models = [] print_models(unprinted_designs, completed_models) show_completed_models(completed_models)
禁止函数修改列表
def print_models(unprinted_designs, completed_models): while unprinted_designs: current_design = unprinted_designs.pop() print("Printing model: " + current_design) completed_models.append(current_design) def show_completed_models(completed_models): print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_model) unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron'] completed_models = [] print_models(unprinted_designs[:], completed_models) show_completed_models(completed_models)
传递任意数量实参
传递任意数量实参
def make_pizza(*toppings): print("\nMaking a pizza with the following toppings:") for topping in toppings: print("- " + topping) make_pizza('pepperoni') make_pizza('mushrooms', 'green peppers', 'extra cheese')
结合使用位置实参和任意数量实参
def make_pizza(size, *toppings): print("\nMaking a " + str(size) + "-inch pizza with the following toppings:") for topping in toppings: print("- " + topping) make_pizza(16, 'pepperoni') make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
使用任意数量的关键字实参
def build_profile(first, last, **user_info): profile = {} profile['first_name'] = first profile['last_name'] = last for key, value in user_info.items(): profile[key] = value return profile user_profile = build_profile('albert', 'einstein', location='princeton', field='physics') print(user_profile)
将函数存储到模块中
导入整个模块
pizza.py def make_pizza(size, *toppings): print("\nMaking a " + str(size) + "-inch pizza with the following toppings:") for topping in toppings: print("- " + topping) making_pizzas.py import pizza pizza.make_pizza(16, 'pepperoni') pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
导入特定的函数
pizza.py def make_pizza(size, *toppings): print("\nMaking a " + str(size) + "-inch pizza with the following toppings:") for topping in toppings: print("- " + topping) making_pizzas.py from pizza import make_pizza make_pizza(16, 'pepperoni') make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
使用as给函数指定别名
pizza.py def make_pizza(size, *toppings): print("\nMaking a " + str(size) + "-inch pizza with the following toppings:") for topping in toppings: print("- " + topping) making_pizzas.py from pizza import make_pizza as mp mp(16, 'pepperoni') mp(12, 'mushrooms', 'green peppers', 'extra cheese')
文件和异常
读取文件
读取整个文件
with open('test.txt') as file_object: contents = file_object.read() print(contents)
根据路径读取文件
file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt' with open(file_path) as file_object: contents = file_object.read() print(contents)
逐行读取文件
filename = 'test.txt' with open(filename) as file_object: for line in file_object: print(line)
创建一个包含文件各行内容的列表
filename = 'test.txt' with open(filename) as file_object: lines = file_object.readlines() for line in lines: print(line.rstrip())
写入文件
写入空文件
filename = 'test.txt' with open(filename, 'w') as file_object: file_object.write("I love programming.")
文件中写入多行
filename = 'test.txt' with open(filename, 'w') as file_object: file_object.write("I love programming.\n") file_object.write("I love creating new games.\n")
在文件后增加内容
filename = 'test.txt' with open(filename, 'a') as file_object: file_object.write("I also love finding meaning in large datasets.\n") file_object.write("I love creating apps that can run in a browser.\n")
异常
使用try-expect代码
try: print(5/0) except ZeroDivisionError: print("You can't divide by zero!")
else代码块
print("Give me two numbers, and I'll divide them.") print("Enter 'q' to quit.") while True: first_number = input("\nFirst number: ") if first_number == 'q': break second_number = input("Second number: ") if second_number == 'q': break try: answer = int(first_number) / int(second_number) except ZeroDivisionError: print("You can't divide by 0!") else: print(answer)
处理 FileNotFoundError 异常
filename = 'alice.txt' try: with open(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file " + filename + " does not exist." print(msg)
多个文件处理
def count_words(filename): """ 计算一个文件大致包含多少个单词 """ try: with open(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file " + filename + " does not exist." print(msg) else: # 计算文件大致包含多少个单词 words = contents.split() num_words = len(words) print("The file " + filename + " has about " + str(num_words) + " words.") filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt'] for filename in filenames: count_words(filename)
存储文件
使用json.dump()存储
import json numbers = [2, 3, 5, 7, 11, 13] filename = 'numbers.json' with open(filename, 'w') as f_obj: json.dump(numbers, f_obj)
使用json.load()读取
import json filename = 'numbers.json' with open(filename) as f_obj: numbers = json.load(f_obj) print(numbers)
保存和读取用户输入
import json # 如果以前存储了用户名,就加载它 # 否则,就提示用户输入用户名并存储它 filename = 'username.json' try: with open(filename) as f_obj: username = json.load(f_obj) except FileNotFoundError: username = input("What is your name? ") with open(filename, 'w') as f_obj: json.dump(username, f_obj) print("We'll remember you when you come back, " + username + "!") else: print("Welcome back, " + username + "!")
类
创建和使用类
创建简单类
class Dog(): """ 一次模拟小狗的简单尝试 """ def __init__(self, name, age): """ 初始化属性 name 和 age""" self.name = name self.age = age def sit(self): 拟小狗被命令时蹲下 """ print(self.name.title() + " is now sitting.") def roll_over(self): """ 模拟小狗被命令时打滚 """ print(self.name.title() + " rolled over!")
根据类创建实例
class Dog(): """ 一次模拟小狗的简单尝试 """ def __init__(self, name, age): """ 初始化属性 name 和 age""" self.name = name self.age = age def sit(self): """拟小狗被命令时蹲下 """ print(self.name.title() + " is now sitting.") def roll_over(self): """ 模拟小狗被命令时打滚 """ print(self.name.title() + " rolled over!") my_dog = Dog('willie', 6) print("My dog's name is " + my_dog.name.title() + ".") print("My dog is " + str(my_dog.age) + " years old.")
使用类和实例
创建一个类
class Car(): """ 一次模拟汽车的简单尝试 """ def __init__(self, make, model, year): """ 初始化描述汽车的属性 """ self.make = make self.model = model self.year = year def get_descriptive_name(self): """ 返回整洁的描述性信息 """ long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name())
给属性指定默认值
class Car(): """ 一次模拟汽车的简单尝试 """ def __init__(self, make, model, year): """ 初始化描述汽车的属性 """ self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """ 返回整洁的描述性信息 """ long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): """ 打印一条指出汽车里程的消息 """ print("This car has " + str(self.odometer_reading) + " miles on it.") my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name()) my_new_car.read_odometer()
直接修改属性的值
class Car(): """ 一次模拟汽车的简单尝试 """ def __init__(self, make, model, year): """ 初始化描述汽车的属性 """ self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """ 返回整洁的描述性信息 """ long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): """ 打印一条指出汽车里程的消息 """ print("This car has " + str(self.odometer_reading) + " miles on it.") my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name()) my_new_car.odometer_reading = 23 my_new_car.read_odometer()
通过方法修改属性的值
class Car(): """ 一次模拟汽车的简单尝试 """ def __init__(self, make, model, year): """ 初始化描述汽车的属性 """ self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """ 返回整洁的描述性信息 """ long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): """ 打印一条指出汽车里程的消息 """ print("This car has " + str(self.odometer_reading) + " miles on it.") def update_odometer(self, mileage): """ 将里程表读数设置为指定的值 """ self.odometer_reading = mileage my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name()) my_new_car.update_odometer(23) my_new_car.read_odometer()
通过方法对属性的值进行递增
class Car(): """ 一次模拟汽车的简单尝试 """ def __init__(self, make, model, year): """ 初始化描述汽车的属性 """ self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """ 返回整洁的描述性信息 """ long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): """ 打印一条指出汽车里程的消息 """ print("This car has " + str(self.odometer_reading) + " miles on it.") def update_odometer(self, mileage): """ 将里程表读数设置为指定的值 """ self.odometer_reading = mileage def increment_odometer(self, miles): """ 将里程表读数增加指定的量 """ self.odometer_reading += miles my_used_car = Car('subaru', 'outback', 2013) 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()
继承
子类的方法__init__()
class Car(): """ 一次模拟汽车的简单尝试 """ def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): print("This car has " + str(self.odometer_reading) + " miles on it.") def update_odometer(self, mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, miles): self.odometer_reading += miles class ElectricCar(Car): """ 电动汽车的独特之处 """ def __init__(self, make, model, year): """ 初始化父类的属性 """ super().__init__(make, model, year) my_tesla = ElectricCar('tesla', 'model s', 2016) print(my_tesla.get_descriptive_name())
给子类定义属性和方法
class Car(): """ 一次模拟汽车的简单尝试 """ def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): print("This car has " + str(self.odometer_reading) + " miles on it.") def update_odometer(self, mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, miles): self.odometer_reading += miles class ElectricCar(Car): """Represent aspects of a car, specific to electric vehicles.""" def __init__(self, make, model, year): """ 电动汽车的独特之处 初始化父类的属性,再初始化电动汽车特有的属性 """ super().__init__(make, model, year) self.battery_size = 70 def describe_battery(self): """ 打印一条描述电瓶容量的消息 """ print("This car has a " + str(self.battery_size) + "-kWh battery.") my_tesla = ElectricCar('tesla', 'model s', 2016) print(my_tesla.get_descriptive_name()) my_tesla.describe_battery()
将实例用作属性
class Car(): """ 一次模拟汽车的简单尝试 """ def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): print("This car has " + str(self.odometer_reading) + " miles on it.") def update_odometer(self, mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, miles): self.odometer_reading += miles class Battery(): """ 一次模拟电动汽车电瓶的简单尝试 """ def __init__(self, battery_size=70): """ 初始化电瓶的属性 """ self.battery_size = battery_size def describe_battery(self): """ 打印一条描述电瓶容量的消息 """ print("This car has a " + str(self.battery_size) + "-kWh battery.") class ElectricCar(Car): """Represent aspects of a car, specific to electric vehicles.""" def __init__(self, make, model, year): """ 电动汽车的独特之处 初始化父类的属性,再初始化电动汽车特有的属性 """ super().__init__(make, model, year) self.battery = Battery() my_tesla = ElectricCar('tesla', 'model s', 2016) print(my_tesla.get_descriptive_name()) my_tesla.battery.describe_battery()
导入类
导入单个类
car.py class Car(): """ 一次模拟汽车的简单尝试 """ def __init__(self, make, model, year): """ 初始化描述汽车的属性 """ self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """ 返回整洁的描述性信息 """ long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): """ 打印一条指出汽车里程的消息 """ print("This car has " + str(self.odometer_reading) + " miles on it.") def update_odometer(self, mileage): """ 将里程表读数设置为指定的值 """ self.odometer_reading = mileage def increment_odometer(self, miles): """ 将里程表读数增加指定的量 """ self.odometer_reading += miles my_car.py from car import Car my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name()) my_new_car.odometer_reading = 23 my_new_car.read_odometer()
在一个模块中存储多个类
car.py class Car(): """ 一次模拟汽车的简单尝试 """ def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): print("This car has " + str(self.odometer_reading) + " miles on it.") def update_odometer(self, mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, miles): self.odometer_reading += miles class Battery(): """ 一次模拟电动汽车电瓶的简单尝试 """ def __init__(self, battery_size=70): """ 初始化电瓶的属性 """ self.battery_size = battery_size def describe_battery(self): """ 打印一条描述电瓶容量的消息 """ print("This car has a " + str(self.battery_size) + "-kWh battery.") class ElectricCar(Car): """Represent aspects of a car, specific to electric vehicles.""" def __init__(self, make, model, year): """ 电动汽车的独特之处 初始化父类的属性,再初始化电动汽车特有的属性 """ super().__init__(make, model, year) self.battery = Battery() my_electric_car.py from car import Car, ElectricCar my_tesla = ElectricCar('tesla', 'model s', 2016) print(my_tesla.get_descriptive_name()) my_tesla.battery.describe_battery() my_tesla.battery.describe_battery()
导入整个模块
import car my_beetle = car.Car('volkswagen', 'beetle', 2016) print(my_beetle.get_descriptive_name()) my_tesla = car.ElectricCar('tesla', 'roadster', 2016) print(my_tesla.get_descriptive_name())
导入模块中所有类
from module_name import *