python程式設計——從入門到實踐總結(函式與類)
阿新 • • 發佈:2020-12-31
文章目錄
一、函式
1)建立函式
def dosomething():
print("hello world")
dosomething()
2)傳遞引數
def introduce(name,age):
print("I am " +name+" and I am "+age)
introduce("Yuji","12")
3) 預設引數
def introduce(name="name",age="12"):
print("I am "+name+" and I am "+age)
introduce()
def introduce(name,age="12"):
print("I am "+name+" and I am " +age)
introduce("lucy")
4)返回值
#要用一個變數來接收返回值
def introduce(name,time):
return name+" "+time
a=introduce("Yuji","15")
print(a)
5)傳遞列表
#不會改變列表,傳引用
def listChange(list):
for i in list:
i=i+" changed"
print(i)
list=["apple" ,"banana","chocolate"]
listChange(list)
print(list)
6)傳遞任意數量的同類實參(傳陣列)
def getPrint(a,*counter):
for i in counter:
print(a+" "+i)
getPrint("Yuji","1",'2','3','4')
7)傳遞任意數量的引數(傳字典)
# age 15
# weight 80
def getPrint(a,**counter):
for key,value in counter.items():
print(key+" "+value+" ")
getPrint("Yuji",age="15",weight="80")
二、匯入函式
有兩個模組
main.py
def hello():
print("hello world")
1)匯入模組
New.py
import main
main.hello()
2)匯入模組並命名
New.py
import main as mn
mn.hello()
3) 匯入函式
New.py
from main import hello
4) 匯入函式並命別名
New.py
from main import hello as h
三、類
1)建立使用類
class Dog():
def __init__(self,name,age):#定義,宣告屬性
self.name=name
self.age=age
def sit(self):#方法
print(self.name+" is sitting");
def changeName(self):#修改屬性
self.name="Ly"
myDog=Dog("Kang","12")#例項化
myDog.sit()
myDog.changeName()#呼叫方法
print(myDog.name)#訪問屬性
2) 繼承
class Dog:#不要帶Dog(),否則報錯
def __init__(self,name):#定義,宣告屬性
self.name=name
def sit(self):#方法
print(self.name+" is sitting");
def changeName(self):#修改屬性
self.name="Yuji"
class BlackDog(Dog):
def __init__(self,name,color):
super().__init__(name)
self.color=color
def sit(self):#重寫
print(self.color)
b=BlackDog("momo","black")
b.sit()
#還可以將例項作為屬性
3) 匯入類
from main import Dog
from main import Dog,BlackDog
from main import *