Python理论 —— 数据类型、基础语法、运算

1. 数据类型

  • 变量命名规则:只能用字母、数字、下划线,且数字不能做开头;

1.1 数字

数字可进行的运算有:(+ ) 减(- ) 乘(* ) 除(/ ) 乘方(**);

1.1.1 整数

不带小数点的数字

1.1.2 浮点数

带小数点的数字

1.1.3 将数字转换为字符串

age = 23 # 定义数字变量
message = "Happy " + str(age)+ "rd Birthday!" # 用函数str把数字转换成字符串

1.2 字符串

  • 定义字符串
‘This is a string!’
# 或
“This is a string!”
# 建议使用双引号,因为双引号内可以用单引号
  • 拼接字符串
first_name = "ada"
last_name = "Olivia"
full_name = first_name + " " + last_name
  • 使用制表符和换行符
print("Languages:\n\tPython\n\tC\n\tJavaScript")
# 制表符:\t
# 换行符:\n

1.2.1 删除字符串中多余的空格

  • rstrip()删除字符串末尾的空格:
favorite_language = 'python '# 字符串最后有一空格
print(favorite_language.rstrip())
  • lstrip()删除字符串开头的空格:
favorite_language = ' python'
print(favorite_language.lstrip())
  • strip()删除字符串开头和结尾的空格:
favorite_language = ' python '
print(favorite_language.strip()) # 一般结合for语句删除列表中的空白和换行符

1.2.2 将字符串转换为数字

int()函数可将字符串转换成整数;

age_0 = input("input your age : ")
age = int(age_0)  #把字符串转换为数值
print(age)

1.2.3 字符串比较

  • 比较两个字符串是否一致:
    a = "a"
    b="b"
    if a is b:
        print("yes")
    else:
        print("no")
	# 运行结果:“no”
####################################
    if a is not b:
        print("yes")
    else:
        print("no")
	# 运行结果:“yes”
  • 另一种方法:
    a = "a"
    b="b"
    if a == b:
        print("yes")
    else:
        print("no")
	# 运行结果:“no”
####################################
    if a != b:
        print("yes")
    else:
        print("no")
	# 运行结果:“yes”

1.2.4 查找字符串中的字符

假设有字符串为:A: 233.00 BBB ;'

if `A: 233.00 BBB ;' in data:
	# 条件成立,进入if 内部

1.2.5 以指定分隔符切片字符串

假设有字符串为:A: 233.00 BBB ;B: 253.00 BBB ;C: 333.00 BBB ;'

list_Data = data.split(';')
# 输出一个列表list_360kHzData,其内容为:[`A: 233.00 BBB `,`B: 253.00 BBB `,`C: 333.00 BBB `]

1.2.6 以指定步长切片字符串(提取字符串中间字符)

假设有字符串为:A: 233.00 BBB ;'

str_s = str_Qs[3:8]
# str_s 打印结果为`233.00`

1.3 列表

列表由一系列按特定顺序有序地排列的元素组成,可包含所有类型的数据;列表元素用方括号[]包含;

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
  • 访问列表元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0])
  • 修改列表元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
bicycles[0] = ‘o’
  • 添加列表元素
# 使用append函数在列表末尾添加元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
bicycles.append(‘h’)
# 使用insert函数在列表指定地方添加元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
bicycles.insert(0,’u’) # 在列表第0个位置添加元素,原先位于该位置的元素将逐一往右移一位
  • 移除列表元素
# 使用del函数删除列表中指定位置的元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
del bicycles[0]
# 使用remove函数删除列表中指定内容的元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
bicycles.remove(‘redline’) #删除列表中所有叫‘redline’的元素
# 使用pop函数弹出列表最后一个元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
poped_bicycles = bicycles.pop()
# 使用pop函数弹出列表中指定位置的元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
poped_bicycles = bicycles.pop(0)
  • 排序列表元素
# 使用sort函数对列表元素进行永久性排序
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
bicucles.sort() # 按字母顺序正序排列(区分大小写,大写的编码在小写之前)
bicucles.sort(reverse = True) # 按字母顺序反序排列(区分大小写,大写的编码在小写之前)
# 使用sorted函数对列表进行临时性排序
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(sorted(bicycles)) # 按字母顺序正序排列(区分大小写,大写的编码在小写之前)
print(bicycles) # 列表的顺序并没有改变
# 使用reverse函数倒置列表
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
bicycles.reverse()
print(bicycles)
  • 读取列表元素数量
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(len(bicycles)) # 输出4

1.3.1 遍历列表

# 使用for语句遍历列表
names = ['caron', 'fine', 'nan']
for name in names:
	print(name)
	print("he’s/She's name is " + name.title() +".\n")

1.3.2 创建列表

lsit = []

1.3.3 创建数值连续的列表

number = list(range(1,6))# 创建的列表包含元素为数值1~5
print(number) # 输出[1, 2, 3, 4, 5]

1.3.4 创建指定步长的数值列表

number = list(range(1,6,2)) # 从1开始逐次加2一直到6(不含)结束
print(number) # 输出[1, 3, 5]

1.3.5 取数字列表中的最值、求和值

digits = [1,2,3,4,5,6,7,8,9,10]
print(min(digits))
print(max(digits))
print(sum(digits))

1.3.6 列表切片

列表切片,顾名思义,就是把列表切成多个片片,与range函数一样,需要指明第一个元素和最后一个元素的索引,Python一直遍历到最后一个索引的前一个位置;

list = [1,2,3,4,5,6]
print(list[0:3]) # 从0到3,输出[1, 2, 3]
print(list[:3]) # 从开头到3,输出[1, 2, 3]
print(list[-3:-1]) # 从倒数第3个到倒数第1个,输出[4, 5]
print(list[:]) # 全切片,输出[1,2,3,4,5,6],一般用于列表复制

在使用函数处理列表时,若不想让函数影响到原列表内容,可用全切片的方式给函数传递一个列表的副本;

def printing_file(unprinted_files,competed_files):
    while unprinted_files:
        current_file = unprinted_files.pop()
        print("the printting file is : " + current_file)
        competed_files.append(current_file)

def show_completed_file(competed_files):
    for competed_file in competed_files:
        print(competed_file)

unprinted_files = ["jerry","tony","risa"]
competed_files = []
printing_file(unprinted_files[:],competed_files) # 给函数传递一个列表副本
print(unprinted_files)
print(competed_files)
print("------------------------------------")
show_completed_file(competed_files)

1.3.7 复制列表

# 用全切片来复制一个列表到新列表
list = [1,2,3,4,5,6]
list2 = list[:] 
list2 = list
print(list)
print(list2)

1.3.8 在列表之间转移元素

unconfromed_user = ["toby","tony","jerry"]
conformed_users = []
while unconfromed_user:
    current_user = unconfromed_user.pop()
    print("current confirming user is " + current_user)
    conformed_users.append(current_user)
    print("now , the confirmed users are : " + str(conformed_users))

1.3.9 删除列表中的特定元素

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
while "cat" in pets :
    pets.remove("cat")
print(pets)

1.4 元组

元组就是不可修改的列表,列表的遍历、切片、提取等语法在元组上一样适用;元组元素用括号()包含;

  • 定义元组和访问元组元素
tuple = (1,2,3,4)
print(tuple)
print(tuple[0])
  • 元组定义后禁止再修改其元素
tuple = (1,2,3,4)
tuple[0] = 6
# 报错:'tuple' object does not support item assignment
  • 元组修改只能通过重新定义
tuple = (1,2,3,4)
for i in tuple:
    print(i)
print("----------")
tuple  = (2,3,4,5)  #重新给元祖赋值
for i in tuple:
    print(i)

1.5 字典

字典是一系列键—值对,与键相关联的值可以是数字、 字符串、 列表甚至字典本身,与列表、元组不同的是,字典内部的键值对是无序的, Python并不关心键值对的顺序,而只关心键和值之间的关联关系;

  • 定义和访问字典
dictionary= {'age' : '20','sex' : 'male','job' : 'teacher'}
print(dictionary)
print(dictionary['age'])  #通过字典中的键访问字典中的值
  • 添加、修改键值对
man = {'age' : '20','sex' : 'male','job' : 'teacher'}
man['style'] = 'free' # 添加键值对
print(man)
man['sex'] = 'female' # 修改键值对
print(man)
  • 删除键值对
man = {'age' : '20','sex' : 'male','job' : 'teacher'}
man['style'] = 'free'
print(man)
del man['style'] # 删除键值对
print(man)

1.5.1 遍历字典

# 全遍历
man = {'age' : '20','sex' : 'male','job' : 'teacher'}
for key , value in man.items():
    print("key : " + key)
    print("value : " + value + "\n")
# 只遍历key、只遍历value
man = {'age' : '20','sex' : 'male','job' : 'teacher'}
for key  in man.keys():
    print("key : " + key)
for value in man.values():
    print("value : " + value)
# 用sorted函数对键或值排序后再遍历,排序规则:数字、大写字母、小写字母
man = {'age' : '20','sex' : 'male','job' : 'teacher'}
for key  in sorted(man): #根据键排序遍历
    print("key : " + key)
for value in sorted(man.values()):
    print("value : " + value)  #根据值排序遍历

1.5.2 剔除重复的键

man = {'age' : '20','sex' : 'male','job' : 'teacher',"job":"doctor"}
for key  in set(man): # 用set函数(集合)来剔除字典中重复的键
    print(key)

1.5.3 字典嵌套

将一系列字典存储在列表中, 或将列表作为值存储在字典中,称为嵌套,可以在列表中嵌套字典、 在字典中嵌套列表甚至在字典中嵌套字典;

# 在列表中嵌套字典
jack = {"chara_1":"male" , "chara_2":"20"}
marry ={"chara_1":"femal" , "chara_2":"18"}
man_list = [jack,marry] 
for man in man_list:
    print(man)
# 打印:
# {'chara_1': 'male', 'chara_2': '20'}
# {'chara_1': 'femal', 'chara_2': '18'}
# 在字典中嵌套列表
jack = {"chara_1":["male", "goodness"], "chara_2":"20"}
marry ={"chara_1":["femal","evil"] , "chara_2":"18"}
for i in jack["chara_1"]:
    print(i)
# 在字典中嵌套字典
users = {
"marry" :{"chara_1":"femal" , "chara_2":"18"},
"toby" :{"chara_1":"male", "chara_2":"21"}
}
for user , user_info in users.items():
    print("the user's name is " + user + " and he(she) is " + user_info['chara_2'])

1.5.4 使用input来填充键值对

responses = {}
pull_active = True
while pull_active:
    name = input("Please input your name : ")
    response = input("Please input your favorite food : ")
    responses[name] = response  #生成键-值对,name为键,response为值;
    repeat = input("Would you like to let another person respond? (y/n) ")
    if repeat == "n":
        pull_active = False
for name,response in responses.items():
    print("hello " + name + " your favorite food is " + response)

2. 基础语法

2.1 条件语句

i=1
if i=1
	print(2) 
i=1
if i=1
	print(2) 
else 
	print(3) 
i=1
if i=1
	print(2) 
elif i=2
	print(3) 
else
	print(4)

2.2 循环语句

2.2.1 while

while条件成立时,一直执行语句内的内容,直到条件不成立为止;

current_num = input("please input a number : ")
num = int(current_num)
while num < 5 :
    print("current number is " + str(num))
    num += 1
  • 由用户决定何时退出输入
text = "please input a number and enter q to quit the program : "
current_num = ""
while current_num != 'q' :
    current_num = input(text)
    if current_num == 'q':
        print("you had quit the program.")
    else:
        num = int(current_num)
        if num < 6:
            while num < 6:
                print("current number is " + str(num))
        else:
            print("your number is larger than 5 ")

2.2.2 for

  • 语法
for iterating_var in sequence:
   statements(s)
  • 例程
fruits = ['banana', 'apple',  'mango'] # 列表
for fruit in fruits:        # 循环打印列表
   print ('当前水果: %s'% fruit)
# for 循环中使用else 
for num in range(10,20):  # 迭代 10 到 20 之间的数字
   for i in range(2,num): # 根据因子迭代
      if num%i == 0:      # 确定第一个因子
         j=num/i          # 计算第二个因子
         print ('%d 等于 %d * %d' % (num,i,j))
         break            # 跳出当前循环
   else:                  # 循环的 else 部分
      print ('%d 是一个质数' % num)

2.2.3 break退出当前循环

break可在while循环中的任何位置,用于立即退出循环体;

text = "please input a number and enter q to quit the program : "
current_num = ""
active = True
while active :
    current_num = input(text)
    if current_num == 'q':
        print("you have quit the program.")
        break
    else:
        num = int(current_num)
        if num < 6:
            while num < 6:
                print("current number is " + str(num))
                num += 1
        else:
            print("your number is larger than 5 ")

2.2.3 continue退出本次循环

continue可在while循环中的任何位置,作用是退出本次循环并返回到判断条件处,根据条件判断结果决定是否继续执行循环体;

current_num = 0
text = "please input a number and enter q to quit the program : "
active = True
while active:
    current_num = input(text)
    num = int(current_num)  
    while num < 100:
        num += 1
        if num % 2 == 0:
            continue
        print(str(num)) # 只打印奇数

2.3 and和or

and即与运算;or即或运算;

list = []
for i in range(0,51):  #创建一个0到50的列表
    list.append(i)
for i in list:
    if i > 20 and i < 40:
        print(i)
# 打印结果为21到39的数字
list = []
for i in range(0,51):  #创建一个0到50的列表
    list.append(i)
for i in list:
    if i < 20 or i > 40:
        print(i)
# 打印结果为0到19和41到50的数字

2.4 in

list = []
for i in range(0, 50):  # 创建一个0到50的列表
    list.append(i)
if 50 in list: # 判断50是否在列表内
    print(True)
else:
    print(False)

2.5 布尔表达式

TrueFalse,底层为10

2.6 input

函数input() 让程序暂停运行, 等待用户输入文本,以回车结束输入, 获取用户输入内容后,将其以字符串的形式存储在一个变量中;

user_name = input("please tell me your name : ")
print("hello " + user_name + " welcome to our web.")
  • while循环实现让用户决定何时结束输入
text = "please input a number and enter `q` to quit the program : "
current_num = ""
while current_num != 'q' : # 程序只会在用户输入 q 时结束输入
    current_num = input(text)
    if current_num == 'q':
        print("you had quit the program.")
    else:
        num = int(current_num)
        if num < 6:
            while num < 6:
                print("current number is " + str(num))
                num += 1
        else:
            print("your number is larger than 5 ")

2.7 标志

在判断很多条件都满足才能继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志,就像C中的Flag位一样;

text = "please input a number and enter q to quit the program : "
current_num = ""
active = True
while active :
    current_num = input(text)
    if current_num == 'q':
        print("you had quit the program.")
        active = False
    else:
        num = int(current_num)
        if num < 6:
            while num < 6:
                print("current number is " + str(num))
                num += 1
        else:
            print("your number is larger than 5 ")

2.8 函数

函数的优点是可将代码块与主程序分离,通过给函数指定描述性名称,可让代码的可读性更高;
在这里插入图片描述

  • 定义函数
def say_hello(name):
    print("hello " + name)
say_hello("Tolstoy")

2.8.1 实参和形参

在3.8节代码中,变量name 是一个形参(函数实现功能所需的一项信息,在函数定义时定义,是实参和函数的桥梁),值Tolstoy是一个实参。实参是调用函数时实际传递给函数的信息;
向函数传递实参的方式很多, 可使用位置实参 ,这要求实参的顺序与形参的顺序相同; 也可使用关键字实参 , 其中每个实参都由变量名和值组成; 还可使用列表和字典。

  • 位置实参
# 按顺序把形参赋值给函数的实参
def pet_info(animal , name):
    print("your pet is " + animal + " , it is - name is : " + name)
pet_info("cat" , "aab")
  • 关键字实参
# 按形参关键字赋值给函数的实参
def pet_info(animal , name):
    print("your pet is " + animal + " , it's name is : " + name)
pet_info(name="aab" , animal="dog") 
  • 实参默认值
    若在调用函数时,没有对对应的形参进行赋值,Python将使用形参已给定的默认值,因此,给形参指定默认值后,可在函数调用中缺省相应的实参,使用形参的默认值。
def pet_info(pet_name ,animal = "dog" ):
    print("your pet is " + animal + " , it's name is : " + pet_name)
pet_info(pet_name="aab")
  • 可选的实参:给要变成可选项的实参指定一个默认值——空字符串,并将其移到形参列表的末尾,即可让该实参变成可选项,调用函数时若实参和形参数量不对应,该可选项实参则被忽略;
def get_name(first_name , last_name , middle_name = ""):
    name = first_name + " " + middle_name + " " + last_name
    return name
name0 = get_name("idw","lee")
print("your name is " + name0)
name1 = get_name(first_name="fillip",middle_name="midd",last_name="lss")
print("your name is " + name1)
# 打印输出:
# your name is idw  lee
# your name is fillip midd lss
  • 任意数量的实参:预先不知道函数需要接受多少个实参时,可用以下方法定义函数形参;
def print_files(*unprinted_files): # 在定义形参时在形参前加*
    for i in unprinted_files:
        print(i)
    print("----------------------")
print_files("risa","folp","strong")
print_files("risa")
print_files("risa","folp","strong","risa","folp","strong")
# 结合位置实参和任意数量的实参一起使用
def print_a_man(gender,*chara):
    print("this user's gender is : " + gender)
    print("his(her) characteristic are : ")
    print(chara)
    print("----------------------")
print_a_man("male","risa","folp","strong")
print_a_man("female")
print_a_man("male","risa","folp","strong","risa","folp","strong")

3.8.2 返回值

函数的返回值可是任意的数据类型,包括列表和字典等较复杂的数据类型;

def get_name(first_name , last_name):
    name = first_name + " " +last_name
    return name
name = get_name("idw","lee")
print("your name is " + name)
  • 返回字典
def get_name(first_name , last_name , middle_name = ""):
    name = {"first":first_name,"last":last_name}
    if middle_name:
        name["middle"] = middle_name
    return name
name0 = get_name("idw","lee")
print(name0)
name1 = get_name(first_name="fillip",middle_name="midd",last_name="lss")
print(name1)
# 打印输出:
# {'first': 'idw', 'last': 'lee'}
# {'first': 'fillip', 'last': 'lss', 'middle': 'midd'}

2.8.3 函数输入值

  • 向函数传递列表:向函数传递列表,这种列表包含的可能是名字、数字或更复杂的对象(如字典),将列表传递给函数后,函数就能直接访问其内容;
# 向函数传入列表
def get_name(name):
    for i in name:
        print("hello " + i)
name0 = ["jerry","tony","risa"]
get_name(name0)

2.8.4 模块与函数

函数可存储在模块中,模块是一个存储函数的文件,在调用模块中的函数时,可用import语句导入该整个模块,然后调用再调用该模块中的函数,也即是说,模块相当于一个封装后的函数库;

使用import导入模块的前提是模块的文件与工程文件在同一路径;

  • 模块文件mode_test.py
def build_profile(first,last,**user_info):
    profile = {}  #创建一个字典,存储用户信息
    profile["first_name"] = first
    profile["last_name"] = last
    for key,value in user_info.items():  #把字典user_info中的键-值对添加到字典profile中
        profile[key] = value
    return profile
  • 工程文件
import mode_test # 引入整个模块
jack_profile = mode_test.build_profile("simmon","jack",age=12,gender="male")
print(jack_profile)
# 打印结果:
# {'first_name': 'simmon', 'last_name': 'jack', 'age': 12, 'gender': 'male'}
2.8.4.1 from...import

以上模块文件不变,使用from...import语句可在该模块中引入特定的函数

from mode_test import build_profile
jack_profile = build_profile("simmon","jack",age=12,gender="male")
print(jack_profile)
2.8.4.2 as

as可给引入的函数改名;也可以给引入的整个模块改名;

# 给引入的函数改名
from mode_test import build_profile as anyName 
jack_profile = adyName("simmon","jack",age=12,gender="male")
print(jack_profile)
# 给引入的整个模块改名
import mode_test as anyName
jack_profile = anyName.build_profile("simmon","jack",age=12,gender="male")
print(jack_profile)
2.8.4.3 *

使用运算符*可导入模块中的所有函数;

from mode_test import *
jack_profile = build_profile("simmon","jack",age=12,gender="male")
print(jack_profile)

2.9 类

类就是一类对象所拥有的通用特征和行为(如人类),对象是类的一个实例化、特殊化(如男人、女人);

  • 创建类:
    类的命名一般首写字母大写,每个类都会有一个__init__函数,且改函数中的self参数必不可少且必须作为函数的第一个形参;函数__init__是类的初始化函数,每当类创建新对象时,Python都会自动运行该函数,函数内一般用于赋予对象一些该类中通用的属性
class Human():
    def __init__(self,name,age):
        #初始化属性name和age
        self.name = name
        self.age = age
    def eat(self):
        print(self.name + " is eating.")
    def play(self):
        print(self.name + " is playing.")
  • 根据类实例化对象
class Human():
    def __init__(self,name,age):
        #初始化属性name和age
        self.name = name
        self.age = age
    def eat(self):
        print(self.name + " is eating.")
    def play(self):
        print(self.name + " is playing.")

jacky = Human('jacky',21) # 根据类实例化一个对象
jacky.play() # 调用类中的方法
jacky.eat()
print("His name is " + jacky.name) # 访问类的属性

2.9.1 给类的属性指定默认值

其原理与给函数形参指定默认值同理;

class Human():
    def __init__(self,name,age,local):
        #初始化属性name和age
        self.name = name
        self.age = age
        self.local = local
        self.father = "null" #给类属性father赋一个默认值
    def eat(self):
        print(self.name + " is eating.")
    def get_complete_info(self):
        complete_info = self.name + " " +str(self.age) + " " + self.local
        return complete_info
    def print_father(self):
        print("His(Her) father is " + self.father)
    def get_father(self,father): # 当然也可以用函数来改变类属性的默认值
        self.father = father


jacky = Human('jacky',21,"Shenzhen")
jacky.print_father() # 使用类默认的属性
jacky.father = "Simon" # 修改类的属性
# jacky.get_father("Simon")  # 使用函数来改变类属性的默认值
jacky.print_father()

2.9.2 继承

如果要编写的类是一个现成类的特殊版本,可使用继承 ;一个类继承另一个类时,它将自动获得其父类的所有属性和方法,这个新类称为子类 ,子类除了继承其父类的所有属性和方法,同时还可以定义自己的属性和方法;创建子类时,父类必须包含在当前文件中,且定义必须位于子类前面;

  • 从父类继承一个子类:在子类中使用函数super().__init__()来将父类的属性继承给子类,因为父类又叫超类(superclass),所以函数名取super
# 父类
class Human():
    def __init__(self,name,age,location):
        self.name = name
        self.age = age
        self.location = location
        self.father = "null" # 给类属性father赋一个默认值
    def eat(self):
        print(self.name + " is eating.")
    def get_complete_info(self):
        complete_info = self.name + " " +str(self.age) + " " + self.location
        return complete_info
    def print_father_name(self):
        print("His(Her) father is " + self.father)
    def get_father_name(self,father):
        self.father = father

# 子类
class Man(Human):
    def __init__(self,name,age,location):
        super().__init__(name,age,location) #继承父类的属性
        self.energy = 100 #子类独有的属性

jacky = Human('jacky',21,"Shenzhen") # 父类实例化
rary = Man("rary",2,"Guangzhou") # 子类实例化
rary.get_father_name("jacky")
rary.print_father_name()
print(rary.get_complete_info())
print("The energy of the kid is " + str(rary.energy))
2.9.2.1 覆盖父类中的函数
# 父类
class Human():
    def __init__(self,name,age,local):
        self.name = name
        self.age = age
        self.local = local
        self.father = "null" #给类属性father赋一个默认值
    def eat(self):
        print(self.name + " is eating.")
    def get_complete_info(self):
        complete_info = self.name + " " +str(self.age) + " " + self.local
        return complete_info
    def print_father(self):
        print("His(Her) father is " + self.father)
    def get_father(self,father):
        self.father = father

# 子类
class Man(Human):
    def __init__(self,name,age,local):
        super().__init__(name,age,local) #继承父类的属性
        self.energy = 100 #子类独有的属性
    def eat(self):  # 函数名与父类中的函数同名,子类的实例将执行子类的函数
        print("Children can not eating yet.")

jacky = Human('jacky',21,"Shenzhen")
rary = Man("rary",2,"Guangzhou")
rary.eat()

2.9.2.2 将一个类作为另一个类的属性

A类可以作为B类的属性,那么B类将可调用A类中的所有属性和函数;

class Human():
    def __init__(self,name,age,local):
        self.name = name
        self.age = age
        self.local = local
        self.father = "null" #给类属性father赋一个默认值
    def eat(self):
        print(self.name + " is eating.")
    def get_complete_info(self):
        complete_info = self.name + " " +str(self.age) + " " + self.local
        return complete_info
    def print_father(self):
        print("His(Her) father is " + self.father)
    def get_father(self,father):
        self.father = father

class Man_like():
    def __init__(self,like_thing = "car"):
        self.like_thing = like_thing
    def print_like_thing(self):
        print("Man like " + self.like_thing)

class Man(Human):
    def __init__(self,name,age,local):
        super().__init__(name,age,local) #继承父类的属性
        self.energy = 100 #子类独有的属性
        self.like_things = Man_like() # 把Man_like类作为Man类的属性
    def eat(self):
        print("Children can not eating yet.")

jacky = Human('jacky',21,"Shenzhen")
rary = Man("rary",2,"Guangzhou")
rary.like_things.print_like_thing()

3. 运算

3.1 求余

求模运算符 %将两个数相除并返回余数,一般利用这一点来判断一个数是奇数还是偶数;

number = input("input a number : ")
num = int(number)
print(num)
if num == 0 :
    print("your number is zero.")
elif num % 2 == 0:
    print("your number is even.")
else:
    print("your number is odd.")

3.2 乘方

value=2
squares = value**2 # 乘两次方
print(squares)

* 其他

*.1 判断列表是否为空列表

list2 = []
if list2: # 若列表中有内容,返回非0
    print("the list is not empty.")
else: # 若列表中无内容,返回0
    print("the list is empty.")

*.2 获取键盘输入值

age = int(input("请输入您的年龄:"))
print("您的年龄是:" + str(age))

*.3 获取系统时间

import datetime

nowTime = datetime.date.today() # 获取今天日期

*.4 保留数值小数点后几位

i = 1.4499999
i = round(i,2)# 保留小数点后2位
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Truffle7电子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值