一 在類中定義的def
# python中def 是用來干什么的? # 可以定義函數,就是定義一個功能。 class People(): def __init__(self): print("參數self的值是: " + str(self)) print("self.__class__ 的值是: " + str(self.__class__)) print("init 方法,跟着類的加載而執行") ''' 1 定義函數的關鍵字 在python中想要定一個函數,必須使用def 關鍵字 2 后面跟函數名 xx 括號里面定義各種行參 def run(行參1,行參數2.....) 3 在class中定義的def 空參時,自動加入self。 在python的類中self代表實例本身,具體來說,是該實例的內存地址。 4 return [表達式] 結束函數,選擇性地返回一個值給調用方。 想要返回啥直接return。 5 沒有return 返回值是一個none def 函數名(行參1,行參數2.....): 寫在類中的def,在沒有行參時,編輯器自動加入一個self 需要的功能 return xx 指定一個返回值 ''' def eat(self): # 沒有行參 print("吃飯") # 未指定返回值 是none def add(a, b): # 定義兩個行參 c = a + b print(c) return c # 返回一個c 指定c作為返回值 ,需要返回啥,就指定啥。
調用函數,查看效果
二 聊一聊 python中的賦值 , 類的初始化。首先看一下什么是賦值
class People(): def __init__(self): print("參數self的值是: " + str(self)) print("self.__class__ 的值是: " + str(self.__class__)) print("init 方法,跟着類的加載而執行") def eat(self): # 沒有行參 print("吃飯") # 未指定返回值 是none def add(a, b): # 定義兩個行參 c = a + b print(c) return c # 返回一個c 指定c作為返回值 ,需要返回啥,就指定啥。 # 這里是將對象people 賦值給 p p = People print(p) # 打印的是同一個對象 print(People) print(id(p)) # id() 函數用於獲取對象的內存地址 二者是相等的 print(id(People)) print("------") # 可以用people對象來調用相關的方法 People.add(2,3)
實例化走一波
class People(): def __init__(self): print("參數self的值是: " + str(self)) print("self.__class__ 的值是: " + str(self.__class__)) print("init 方法,跟着類的加載而執行") def eat(self): # 沒有行參 print("吃飯") # 未指定返回值 是none def add(a, b): # 定義兩個行參 c = a + b print(c) return c # 返回一個c 指定c作為返回值 ,需要返回啥,就指定啥。 # 實例化和賦值的區別在於 加上了() p = People() # 實例化了一個對象people __init__ 方法會自動執行 print("------------") print(p) # 1 打印的是一個實例對象 <__main__.People object at 0x10133dd00> 2 打印的結果和print(self)相同,都是代表這個實例。
調用der 方法
class People(): def __init__(self): print(self) print(self.__class__) print("init 方法,跟着類的加載而執行") def eat(self): # 沒有行參 print("吃飯") # 未指定返回值 是none def add(a, b): # 定義兩個行參 c = a + b print(c) return c # 返回一個c 指定c作為返回值 ,需要返回啥,就指定啥。 # 實例化和賦值的區別在於 加上了() p = People() # 實例化了一個對象people __init__ 方法會自動執行 print("------------") print(p) # 1 打印的是一個實例對象 <__main__.People object at 0x10133dd00> 2 打印的結果和print(self)相同,都是代表這個實例。 p.eat() p.add(3,4)