赞
踩
| 数值类型( 整数、浮点数、复数 )
| 字节类型( 字符串、字节串 )
| 集合、元组、列表、字典 |
可变数据类型:list(列表)、dict(字典)、set(集合,不常用)
不可变数据类型:数值类型(int、float、bool)、string(字符串)、tuple(元组)
二进制:以0b或0B开头:0b1101,-0B10;
八进制:以0o或0O开头:0o456,-0O789;
十进制:123,-321,0;
十六进制:以0x或0X开头:0x1A,-0X2B。
print(1+3)
# 4
round()
辅助浮点数运算,消除不确定尾数。
print(0.1+0.2111)
# 0.30000000000000004
print(round(0.1+0.2111,5))
# 0.3111
a = 3 + 2j
print(a)
# (3+2j)
print(type(a))
# <class 'complex'>
print(str(a.real) +":" + str(a.imag))
# 3.0:2.0
列表[]、元组()、字典{}
>>> print("hello python")
hello python
或者
C:\Users\Administrator\Desktop>python "hello python.py"
hello python
message = "hello 变量"
print(message)
在程序中可随时修改变量的值,而Python将始终记录变量的最新值。
message = "hello 变量"
print(message)
message = "hello 第二个变量"
print(message)
message = "hello 第二个变量"
print(mesage)
Traceback (most recent call last):
File "main.py", line 5, in <module>
print(mesage)
NameError: name 'mesage' is not defined
Traceback会指出错误行,并且什么地方出错。
字符串就是一系列字符。在Python中,用引号括起的都是字符串,其中的引号可以是单引号,也可以是双引号。
print("string1'hello',hello2")
print('string2')
str1 = "abcd efg"
str2 = str1.title()
print(str2)
str3 = "Abcd Efg"
print(str3 + "==upper:"+str3.upper())
print(str3 + "==lower:"+str3.lower())
str3 = "Abcd Efg"
print("拼接字符串:"+str3+""+str3)
message1 = "hello python"
message2 = "hello\tpython"
print(message1)
print(message2)
message1 = "hello python"
message2 = "hello\tpython"
message3 = "hello\npython"
print(message1)
print(message2)
print(message3)
message1 = "python "
message2 = " python "
print(message1.rstrip()+"!")
print("!"+message2.lstrip()+"!")
message1 = "python "
message2 = " python "
print(message1.rstrip()+"!")
print("!"+message2.lstrip()+"!")
print("!"+message2.lstrip().rstrip()+"!")
print("!"+message2.lstrip(" ").rstrip(" ")+"!")
a = 5/2
aa = 5//2
b = 5*2
bb = 5**2
c = 5+2.1
d = 5-6
e = (5-8)**2
print(a)
print(aa)
print(b)
print(bb)
print(c)
print(d)
print(e)
age = 22
message = "hello" + str(age)
print(message)
使用 # 号
# age = 22
# message = "hello" + str(age)
# print(message)
list = ['123','python','java_SE']
print(list)
print(list[0])
print(list[2].title())#首字母大写显示
print(list[-1])#访问最后一个元素
-2返回倒数第二个元素,-3返回倒数第三个元素,以此类推。
list = ["java",'mysql','pgsql'] # 末尾添加元素 list.append("python") # 列中添加元素 list.insert(1,"C++") # 列中删除元素 del list[1] print(list) # 使用pop弹出末尾元素 last = list.pop() print(last) print(list) #使用pop弹出指定位置元素 list.pop(0) print(list) #根据值删除元素 list.remove('mysql') print(list)
words = ["exe","zzz","aAa","ppp"]
# 对列表永排序
words.sort()
print(words) #['aAa', 'exe', 'ppp', 'zzz']
#反序排列
words.sort(reverse=True)
print(words) #['zzz', 'ppp', 'exe', 'aAa']
words_1 = ["exe","zzz","aAa","ppp"]
# 临时排序
print(sorted(words_1)) #['aAa', 'exe', 'ppp', 'zzz']
words = ["exe","zzz","aAa","ppp"]
# 永久反转顺序
words.reverse()
print(words) #['ppp', 'aAa', 'zzz', 'exe']
words = ["exe","zzz","aAa","ppp"]
print(len(words)) # 4
people = ["小黑","小红","小蓝"]
for i in people:
print(i)
# 小黑
# 小红
# 小蓝
for value in range(1,5):
print(value)
# 1
# 2
# 3
# 4
list = []
for i in range(0,10):
list.append(i)
print(list) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(max(list)) #9
print(min(list)) #0
print(sum(list)) #45
squares = [value**2 for value in range(1,10)]
print(squares) #[1, 4, 9, 16, 25, 36, 49, 64, 81]
切片:处理列表部分元素。指定要使用的第一个元素和最后一个元素的索引。和range()一样,到达指定索引前一个元素停止。
players = ["james","kevin","irving","love"]
# 取 索引0 到 索引2 的所有元素
print(players[0:3]) # ['james', 'kevin', 'irving']
# 取列表2~4个的元素 ; 索引1 到 索引3 的所有元素
print(players[1:4]) #['kevin', 'irving', 'love']
不指定开始索引,则从列表开头取;反之同理:
# 不指定索引
print(players[:4])
#['james', 'kevin', 'irving', 'love']
print(players[1:])
#['kevin', 'irving', 'love']
输出列表最后三个元素:
print(players[-3:])
#['kevin', 'irving', 'love']
for player in players[:3]:
print(player.title())
# James
# Kevin
# Irving
players = ["james","kevin","irving","love"]
copyPL = players[:]
print(copyPL) #['james', 'kevin', 'irving', 'love']
players.append("old")
copyPL.append("new")
#证明两者不是
print(players) #['james', 'kevin', 'irving', 'love', 'old']
print(copyPL) #['james', 'kevin', 'irving', 'love', 'new']
# 元组 # 使用() dimension = (200, 50) print(dimension) print(type(dimension)) # (200, 50) # <class 'tuple'> # 不加括号 dimension_1 = 200, 50 print(dimension_1) print(type(dimension_1)) # (200, 50) # <class 'tuple'> # 使用tuple dimension_2 = tuple((200, 50)) print(dimension_2) print(type(dimension_2)) # (200, 50) # <class 'tuple'> # 单个需要加逗号 不然就是对应类型 dimension_3 = ('sss') print(dimension_3) print(type(dimension_3)) # sss # <class 'str'>
# 元组
dimension = (200,50)
for i in dimension:
print(i)
相比列表,元组是更简单的数据结构。如果要存储一组值在整个生命周期里不变,可使用元组。
list 是可变的对象,元组 tuple 是不可变的对象。
# if
cars = ['audi','bmw','subaru']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.lower())
# audi
# BMW
# subaru
age = 17
if age>=18 :
print(age)
else:
print("too young")
#too young
age = 17
if age<18:
print("too young")
elif age == 18:
print("just enough")
else:
print("right")
# too young
age = 12
if age < 10:
price = 1
elif age > 10 and age < 15:
price = 2
elif age > 15:
price = 3
else:
price = 4
print(price) #2
a = 10
if a == 10:
pass
else:
pass
一个等号是陈述,两个等号是发问返回True和False。
判断时会判定大小写不同。若大小写无影响,可转换大小写进行比较。
car = 'bmw';
print(car == 'bmw') #True
print(car == 'BMW') #False
判断两个值不同:!=
and将两个条件测试合二为一,每个表达式都通过,则为True;
or只要有一个语句满足条件,则为True。所有条件不满足,表达式为False;
example = ('abs','AAA','K','3A')
print('AAA' in example) #True
aliens = {'color': 'red', 'points': '5'}
#[]方法
print(aliens['color']) #red
print(aliens['points']) #5
# get方法
print(aliens.get('color'))
# red
aliens = {'color':'red','points':'5'}
aliens['hight'] = 30
aliens['weight'] = 1000
print( aliens )
# {'color': 'red', 'points': '5', 'hight': 30, 'weight': 1000}
aliens = {'color':'red','points':'5'}
aliens['hight'] = 30
aliens['weight'] = 1000
print( aliens )
# {'color': 'red', 'points': '5', 'hight': 30, 'weight': 1000}
del aliens['weight']
print( aliens )
# {'color': 'red', 'points': '5', 'hight': 30}
aliens = {'color':'red','points':'5'}
aliens['color'] = 'yellow'
print( aliens )
# {'color': 'yellow', 'points': '5'}
user = {"username":"kevin",
"age":"22",
"gender":"male"}
for key,value in user.items():
print("key:"+key+" value:"+value)
# key:username value:kevin
# key:age value:22
# key:gender value:male
user = {"username":"kevin",
"age":"22",
"gender":"male"}
# 获取keys
for i in user.keys():
print(i)
# username
# age
# gender
aliens = {'color': 'red', 'points': '5'}
for i in aliens:
print(i, aliens[i], aliens.get(i))
# color red red
# points 5 5
user = {"username":"kevin",
"age":"22",
"gender":"male"}
for i in user.values():
print(i)
# kevin
# 22
# male
for i in aliens.items():
print(i)
for j in i:
print(j)
# ('color', 'red')
# color
# red
# ('points', '5')
# points
# 5
keys = ['books', 'tools']
price = [11, 21, 31]
for i in zip(keys, price):
print(i)
# ('books', 11)
# ('tools', 21)
for k, p in zip(keys, price):
print(k, p)
# books 11
# tools 21
alien_o = {'color': 'green ', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red ', 'points': 15}
aliens = [alien_o, alien_1, alien_2]
for alien in aliens:
print(aliens)
# [{'color': 'green ', 'points': 5}, {'color': 'yellow', 'points': 10}, {'color': 'red ', 'points': 15}]
# [{'color': 'green ', 'points': 5}, {'color': 'yellow', 'points': 10}, {'color': 'red ', 'points': 15}]
# [{'color': 'green ', 'points': 5}, {'color': 'yellow', 'points': 10}, {'color': 'red ', 'points': 15}]
print(type(aliens))
# <class 'list'>
切片打印前五个
aliens = []
for alien in range(30):
new_alien = {'color':'red ', 'points':15}
aliens.append(new_alien)
for alien in aliens[:5]:
print(alien)
print("...")
# {'color': 'red ', 'points': 15}
# {'color': 'red ', 'points': 15}
# {'color': 'red ', 'points': 15}
# {'color': 'red ', 'points': 15}
# {'color': 'red ', 'points': 15}
# ...
example = {
"user":["james","kevin","tom"],
"password":"123456"
}
print(example["user"]) #['james', 'kevin', 'tom']
print(example["password"]) #123456
example = {
"example_1" : {"user":["james","kevin","tom"],"password":"123456"},
"example_2" : ["list1","list2","list3"],
"example_3" : "example_3"
}
print(example)
#{'example_1': {'user': ['james', 'kevin', 'tom'], 'password': '123456'}, 'example_2': ['list1', 'list2', 'list3'], 'example_3': 'example_3'}
print( example["example_1"])
#{'user': ['james', 'kevin', 'tom'], 'password': '123456'}
# 使用{}
s = {1, 23, 4, 345, 1, 2, 2}
print(s, type(s))
# {1, 2, 4, 23, 345} <class 'set'>
# 使用set()
s1 = set(range(5))
print(s1, type(s1))
# {0, 1, 2, 3, 4} <class 'set'>
language = {"james":"c++",
"kevin":"python",
"bob":"java",
"lily":"python"}
for i in set(sorted(language.values())):
print(i)
# python
# java
# c++
ss = {123, 123, 1, 4, 124, 2} print(ss) # {1, 2, 4, 123, 124} print(123 in ss) # True ss.add("11") print(ss) # {1, 2, '11', 4, 123, 124} ss.update({"22", "222", "2222"}) print(ss) # {'222', 1, 2, '22', 4, '11', '2222', 123, 124}
# 两个集合是否相等 元素相同就相同 s = {10, 20, 30, 40, 50} s1 = {40, 30, 20, 10, 50} print(s == s1) # True # 判断子集 s2 = {10, 20} print(s2.issubset(s)) # True s3 = {10, 21, 22} print(s3.issubset(s)) # False # 判断超集 print(s1.issuperset(s2)) # True print(s3.issuperset(s2)) # False # 交集 print(s2.isdisjoint(s1)) # False 有交集为False
name = input()
print(name)
Python2.7,应使用函数raw input()来提示用户输入。这个函数与Python3中的input ()一样,也将输入解读为字符串。
sentence = "hello please inuput:"
message = ""
message = input(sentence)
print(message)
# hello please inuput:dwadaw
# dwadaw
current_num = 1
while current_num <= 5:
print(str(current_num) + " ", end = "")
current_num+=1
# 1 2 3 4 5
python 3.x版本输出不换行格式如下
print(x, end=“”) end=“” 可使输出不换行。
# 使用while循环,当输入exit才停止 sentence = "Display entered:" message = input("input message - exit or others :\n") while message != "exit": message = input(sentence + message) print(message) # input message - exit or others : # hello # Display entered:hello # # Display entered:abc # abc # Display entered:abc # # Display entered:exit # exit
# while中使用标志 当flag不为True时,停止while循环
sentence = "Display entered:"
message = input("input message - exit or others :\n")
flag = True
while flag:
if message != "exit":
message = input(sentence + message)
print(message)
else:
flag = False
# 使用break 退出循环
falg = True
variable1 = 1
while falg:
if variable1 <=5:
print(variable1 , end = "")
variable1 += 1
else:
break
# 12345
# 循环中使用 continue
current_number = 0
while current_number <10:
current_number += 1
if current_number % 2 ==0:
continue #跳过本次,执行后面代码
print(current_number, end="") #13579
处理列表
#验证账户 while unconfirmed: current = unconfirmed.pop() print("verifying : "+current.title()) confirmed.append(current) print("unconfirmed:") for i in unconfirmed: print(i.title()) print("all confirmed:") for i in confirmed: print(i.title()) # verifying : Tom # verifying : Kevin # verifying : James # unconfirmed: # all confirmed: # Tom # Kevin # James
#删除包含特定值的所有列表元素
pets = [ "dog","cat","dog","goldfish","cat","rabbit","cat" ]
print(pets)
while "cat" in pets:
pets.remove("cat")
print( pets)
# ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
# ['dog', 'dog', 'goldfish', 'rabbit']
处理字典
# 使用用户输入填充字典 rs_responses = {} flag = True while flag: name = input("what's your name?") response = input("what's your favorite weather?") # 存进字典 rs_responses[name] = response repeat = input("would you like to continue? yes/no") if repeat == "no": flag = False print( rs_responses ) # what's your name?james # what's your favorite weather?daylight # would you like to continue? yes/noyes # what's your name?kevin # what's your favorite weather?rainday # would you like to continue? yes/nono # {'james': 'daylight', 'kevin': 'rainday'}
# 问候语简单函数
def greet_user():
print("hello!")
greet_user() #hello!
def greet_user(username):
print("hello!" + username.title() + "!")
greet_user("tom") #hello!Tom!
def describe_pet(animal_type, pet_name):
print("I have a " + animal_type)
print("My " + animal_type + " name is " + pet_name)
describe_pet("dog", "wangwang")
#I have a dog
# My dog name is wangwang
def describe_pet(animal_type, pet_name):
print("I have a " + animal_type)
print("My " + animal_type + " name is " + pet_name)
describe_pet(pet_name="wangwang", animal_type="dog")
#I have a dog
#My dog name is wangwang
def describe_pet(pet_name, animal_type="dog"):
# def describe_pet(animal_type="dog",pet_name): 报错
print("My " + animal_type + " name is " + pet_name)
describe_pet(pet_name="wangwang")
# My dog name is wangwang
使用return语句返回值到调用函数代码行
def get_formatted_name(first_name,last_name):
full_name = first_name+" "+last_name
return full_name.title()
worker = get_formatted_name("tom","kin")
print(worker) #Tom Kin
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()
worker = get_formatted_name("tom", "kin")
print(worker) # Tom Kin
worker2 = get_formatted_name("tom", "kin", "ray")
print(worker2) # Tom Ray Kin
函数可以返回任何值,包含字典与数据结构;
# 返回字典
def build_person(first_name, last_name):
person = {'first': first_name, 'last': last_name}
return person
worker = build_person("will", "smith")
print(worker) #{'first': 'will', 'last': 'smith'}
# 结合函数使用while循环 def get_username(first_name, last_name): full_name = first_name + " " + last_name return full_name.title() while True: print("please input your name: enter q or others to quit; y to continue") variable = input("input your choice:") if variable == "y": first_name = input("please input your first name:") last_name = input("please input your last name:") rs = get_username(first_name, last_name) print(rs.title()) else: break # please input your name: enter q or others to quit; y to continue # input your choice:y # please input your first name:yh # please input your last name:l # Yh L # please input your name: enter q or others to quit; y to continue # input your choice:q
# 传递列表
def get_username(names):
# 向列表每个元素都发出简单问候
for i in names:
msg = "hello " + i.title()
print(msg)
users = ['james', 'tom', 'kevin']
get_username(users)
# hello James
# hello Tom
# hello Kevin
# 函数修改列表 users = ['tom', 'james', 'kevin'] temp_list = [] # 模拟交换每个用户 def change_user(original_list, rs_list): while users: temp_variable = original_list.pop() print("user :" + temp_variable) rs_list.append(temp_variable) def show_users(rs_list): print(rs_list) change_user(users, temp_list) show_users(temp_list)
使用切片,相当于传值给一个临时变量 change_user(users[:], temp_list) ,user[]内容将不会被pop。
# 禁止函数修改列表 users = ['tom', 'james', 'kevin'] temp_list = [] def change_user(original_list, rs_list): while original_list: temp_variable = original_list.pop() print("user :" + temp_variable) rs_list.append(temp_variable) def show_users(rs_list): print(rs_list) # 使用切片 change_user(users[:], temp_list) show_users(users) show_users(temp_list) # user :kevin # user :james # user :tom # ['tom', 'james', 'kevin'] # ['kevin', 'james', 'tom']
预先不知道函数需要接受多少个实参
def print_users(*user):
print(user)
customer_1 = ["example1"]
customer_2 = ["example1", "example2", "example3"]
print_users(customer_1) # (['example1'],)
print_users(customer_2) # (['example1', 'example2', 'example3'],)
*user创建一个空元组
如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。
def make_pizz(size, *type):
for i in type:
print(str(size) + i)
make_pizz(1, 'a')
make_pizz(3, 'a', 'b', 'c')
# 1a
# 3a
# 3b
# 3c
**user_info两个星号让python创建一个user_info的空字典,并将收到的所有键值对都装到这个字典;
# ** 创建字典
def build_profile(firstname, lastname, **user_info):
profile = {}
profile['firstname'] = firstname
profile['lastname'] = lastname
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('james', 'kevin', place="China", fild="physics")
print(user_profile)
创建一个python文件,pizza.py
def make_pizza(size, *toppings):
"""概述要执着的披萨"""
print("\nMaking a " + str(size) + "inch pizza")
for i in toppings:
print("-" + i)
同级目录中main.py 导入模块
import pizza
pizza.make_pizza(16, "pepperoni")
pizza.make_pizza(12, "chicken", "green pepper")
# Making a 16inch pizza
# -pepperoni
#
# Making a 12inch pizza
# -chicken
# -green pepper
from module_name import function_0,function_1,functrion_2
创建一个python文件,pizza.py
def make_pizza(size, *toppings):
"""概述要执着的披萨"""
print("\nMaking a " + str(size) + "inch pizza")
for i in toppings:
print("-" + i)
def make_pizza_1(size,*topping):
print("另外一个函数")
同级目录中main.py 导入模块
from pizza import make_pizza,make_pizza_1
make_pizza(16, "pepperoni")
make_pizza_1(12, "chicken", "green pepper")
# Making a 16inch pizza
# -pepperoni
# 另外一个函数
给make_pizza 指定别名mp()
# as指定函数别名
# 给make_pizza 指定别名mp()
from pizza import make_pizza as mp
mp(16, "pepperoni")
# Making a 16inch pizza
# -pepperoni
import module_name as m
# 使用as 给模块取别名
# import module_name as m
import pizza as p
p.make_pizza(11,"green pepper")
# Making a 16inch pizza
# -pepperoni
使用星号(*)运算符可让Python导入模块中的所有函数:
pizza.py
def make_pizza(size, *toppings):
"""概述要执着的披萨"""
print("\nMaking a " + str(size) + "inch pizza")
for i in toppings:
print("-" + i)
def make_pizza_1(size,*topping):
print("另外一个函数")
main.py
from pizza import *
make_pizza(11,"11")
make_pizza_1(22,"22")
# Making a 11inch pizza
# -11
# 另外一个函数
创建小狗类:
class Dog:
#class Dog(): 这样定义类也可以
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(self.name.title() + " sit down")
def roll_over(self):
print(self.name.title + " rolled over")
1、方法__init__
类中的函数称为方法
方法__init__
是一个特殊的方法,每当你根据dog类创建新实例时,Pyton都会自动运行它。
在这个方法的名称中,开头和末尾各有两个下划线,这是一种约定,旨在避免Pytiomn默认方法与普通方法发生名称冲突。
我们将方法__init__
定义成了包含三个形参: self、 name和age。在这个方法的定义中,形参self必不可少,还必须位于其他形参的前面。为何必须在方法定义中包含形参self呢?因为Pythom调用这个__init__
方法来创建dog实例时,将自动传入实参self。每个与类相关联的方法调用都自动传递实参self,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法。我们创建dog实例时,Python将调用dog类的方法__init__
。我们将通过实参向dog ()传递名字和年龄,self会自动传递,因此我们不需要传递它。每当我们根据Dog类创建实例时,都只需给最后两个形参(name和age 〉提供值。
class Dog(): def __init__(self, name, age): self.name = name self.age = age def sit(self): print(self.name.title() + " sit down") 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() + ", age " + str(my_dog.age)) # my dog's name is Willie, age 6 my_dog.sit() # Willie sit down my_dog.roll_over() # Willie rolled over your_dog = Dog("james", 2) your_dog.sit() your_dog.roll_over() # James sit down # James rolled over
# 指定默认值 class Car(): def __init__(self, make, model, year): self.make = make self.model = model self.year = year # 添加一个属性 始终为0 self.test = 0 def get_descript_car(self): longname = self.make + self.model + str(self.year) return longname def read_test(self): print("car mileage is " + str(self.test)) my_new_car = Car("audi", "a4", 2016) my_new_car.read_test() # car mileage is 0
3、修改属性值
# 指定默认值 class Car: #class Car(): 这样定义类也可以 def __init__(self, make, model, year): self.make = make self.model = model self.year = year # 添加一个属性 始终为0 self.test = 0 def get_descript_car(self): longname = self.make + self.model + str(self.year) return longname def read_test(self): print("car mileage is " + str(self.test)) # 方法修改属性值 def update_test(self, mileage): self.test = mileage # 方法递增 def increment_test(self, miles): self.test += miles my_new_car = Car("audi", "a4", 2016) my_new_car.read_test() # car mileage is 0 # 1、直接修改属性值 my_new_car.test = 22 my_new_car.read_test() # car mileage is 22 # 2、通过方法修改属性值 my_new_car.update_test(50) my_new_car.read_test() # car mileage is 50 # 3、通过方法对属性值进行递增 有时候需要将属性值递增特定的量,而不是将其设置为全新的值。 my_new_car.increment_test(99) my_new_car.read_test() # car mileage is 149
编写类时,并非总是要从空白开始。如果你要编写的类是另一个现成类的特殊版本,可使用继承。
一个类继承另一个类时,它将自动获得另一个类的所有属性和方法,原有的类称为父类,而新类称为子类。
子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法。
# 模拟汽车 class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.mileage = 0 def get_car(self): print(self.make + " " + self.model + " " + str(self.year) + " : " + str(self.mileage) + " mileage") def read_mileage(self): print(self.mileage) def update_mileage(self, mile): if mile > self.mileage: self.mileage = mile else: print("can't roll back mileage") def increment_mileage(self, mile): self.mileage += mile # 模拟电动汽车 class ElectricCar(Car): def __init__(self, make, model, year): super().__init__(make, model, year) my_tesla = ElectricCar("tesla", "model s", 2016) my_tesla.get_car() # tesla model s 2016 : 0 mileage
# 模拟汽车 class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.mileage = 0 self.gas = 100 def get_car(self): print(self.make + " " + self.model + " " + str(self.year) + " : " + str(self.mileage) + " mileage") def read_mileage(self): print(self.mileage) def update_mileage(self, mile): if mile > self.mileage: self.mileage = mile else: print("can't roll back mileage") def increment_mileage(self, mile): self.mileage += mile def fill_gas_tank(self): print("car gas tank : " + str(self.gas)) # 模拟电动汽车 class ElectricCar(Car): def __init__(self, make, model, year): super().__init__(make, model, year) # 子类定义属性 self.batter_size = 100 # 定义子类特定的方法 def describe_battery(self): # 容量 print("capacity : " + str(self.batter_size)) # 重写fill_gas_tank def fill_gas_tank(self): print("electricCar dont need gas tank") # 继承 my_tesla = ElectricCar("tesla", "model s", 2016) my_tesla.get_car() # tesla model s 2016 : 0 mileage # 定义子类特定的方法 my_tesla.describe_battery() # capacity : 100
# 模拟汽车 class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.mileage = 0 self.gas = 100 def get_car(self): print(self.make + " " + self.model + " " + str(self.year) + " : " + str(self.mileage) + " mileage") def read_mileage(self): print(self.mileage) def update_mileage(self, mile): if mile > self.mileage: self.mileage = mile else: print("can't roll back mileage") def increment_mileage(self, mile): self.mileage += mile def fill_gas_tank(self): print("car gas tank : " + str(self.gas)) # 模拟电动汽车 class ElectricCar(Car): def __init__(self, make, model, year): super().__init__(make, model, year) # 子类定义属性 self.batter_size = 100 # 定义子类特定的方法 def describe_battery(self): # 容量 print("capacity : " + str(self.batter_size)) # 重写fill_gas_tank def fill_gas_tank(self): print("electricCar dont need gas tank") # 继承 my_tesla = ElectricCar("tesla", "model s", 2016) my_tesla.get_car() # tesla model s 2016 : 0 mileage # 定义子类特定的方法 my_tesla.describe_battery() # capacity : 100 # 重写父类方法 my_tesla.fill_gas_tank() # electricCar dont need gas tank
from car import Car
import语句让Python打开模块car.py ,并导入其中的Car类。
ElectricCar.py
# 模拟汽车 class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.mileage = 0 self.gas = 100 def get_car(self): print(self.make + " " + self.model + " " + str(self.year) + " : " + str(self.mileage) + " mileage") def read_mileage(self): print(self.mileage) def update_mileage(self, mile): if mile > self.mileage: self.mileage = mile else: print("can't roll back mileage") def increment_mileage(self, mile): self.mileage += mile def fill_gas_tank(self): print("car gas tank : " + str(self.gas)) # 模拟电动汽车 class ElectricCar(Car): def __init__(self, make, model, year): super().__init__(make, model, year) # 子类定义属性 self.batter_size = 100 # 定义子类特定的方法 def describe_battery(self): # 容量 print("capacity : " + str(self.batter_size)) # 重写fill_gas_tank def fill_gas_tank(self): print("electricCar dont need gas tank")
新建一个名为my_electric_car.py的文件,导入ElectricCar类,并创建一辆电动汽车了:
from ElectricCar import ElectricCar
my_tesla = ElectricCar('tesla', 'model', 2021)
my_tesla.get_car() # tesla model 2021 : 0 mileage
from ElectricCar import Car, ElectricCar
你还可以导入整个模块,再使用句点表示法访问需要的类。这种导入方法很简单,代码也易于阅读。
import car
my_tesla = car.Car("audi", "a4", 2021)
print(my_tesla.get_descript_car()) # audia42021
from module_name import *
from collections import OrderedDict favorite_language = OrderedDict() favorite_language['jen'] = 'python' favorite_language['sarah'] = 'java' favorite_language['tom'] = 'ruby' favorite_language['phil'] = 'python' for name, language in favorite_language.items(): print(name.title() + "'s favorite language is " + language.title() + ".") # Jen's favorite language is Python. # Sarah's favorite language is Java. # Tom's favorite language is Ruby. # Phil's favorite language is Python.
蓝色。通过组合不同的RGB值,可创建1600万种颜色。在颜色值(230, 230, 230)中,红色、蓝色和绿色量相同,它将背景设置为一种浅灰色。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。