类函数不带任何参数
class People:
age=20
occupation="程序员"
height=180
name="小明"
def cook(self):
print("他会做粤菜,川菜")
def repair(self):
print("他会修电脑,修电视")
test=People() #创建对象
test.cook() #实例调用类方法
------------------打印结果------------------
他会做粤菜,川菜
类函数调用类属性
class People:
age=20
occupation="程序员"
height=180
name="小明"
def cook(self):
print("{}他会做粤菜,川菜".format(self.name))
def repair(self):
print("他会修电脑,修电视")
test=People() #创建对象
test.cook() #实例调用类方法
------------------打印结果------------------
小明他会做粤菜,川菜
(如果类函数里面要调用类属性,必须要在类属性之前加self关键字,调用的方法是 self.类属性名)
类函数带有位置函数
class People:
age=20
occupation="程序员"
height=180
name="小明"
def cook(self,name):
print("{}他会做粤菜,川菜".format(name))
def repair(self):
print("他会修电脑,修电视")
test=People() #创建对象
test.cook("张三李四王五") #实例调用类方法
--------------------------打印结果--------------------------
张三李四王五他会做粤菜,川菜
类函数带有默认参数
class People:
age=20
occupation="程序员"
height=180
name="小明"
def cook(self,name="神厨小福贵"):
print("{}他会做粤菜,川菜".format(name))
def repair(self):
print("他会修电脑,修电视")
test=People() #创建对象
test.cook() #实例调用类方法,不传入参数
test.cook("小美") #实例调用类方法,传入参数
------------------------打印结果------------------------
神厨小福贵他会做粤菜,川菜
小美他会做粤菜,川菜
类的初始化函数:__init__(self)
class People:
def __init__(self,age,occupation,height,name):
self.age=age
self.occupation=occupation
self.height=height
self.name=name
def cook(self):
print("他会做粤菜,川菜")
def repair(self):
print("他会修电脑,修电视")
test=People(20,"厨师",180,"喜洋洋")
test.cook()
print(test.occupation)
-------------------打印结果-------------------
他会做粤菜,川菜
厨师
类函数调用初始化值
class People:
def __init__(self,age,occupation,height,name):
self.age=age
self.occupation=occupation
self.height=height
self.name=name
def cook(self):
print("{},他会做粤菜,川菜".format(self.name))
def repair(self):
print("{}他会修电脑,修电视".format(self.occupation))
test=People(20,"厨师",180,"喜洋洋")
test.cook()
test.repair()
-------------------------打印结果-------------------------
喜洋洋,他会做粤菜,川菜
厨师他会修电脑,修电视
(如果类函数里面要调用初始化值,可以直接调用,记得加self关键字)