def 方法名(self,参数):
在方法内部,是可以通过self.属性/方法,来调用对象的其他属性或者方法
实例化类,创建对象
1、创建对象的语法
对象名=类名(参数) __init__ 函数有参就要传参,没有就不要传
2、可以创建多个对象
3、每个对象都是独立的,每个对象都拥有类里面的所有方法
4、每个对象的属性、方法调用
对象名. 方法()
对象名. 属性
获取类型属性的办法:
class People:
add="信息表"
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("他会修电脑,修电视")
print(People.add)
test=People(20,"厨师",180,"喜洋洋")
print(test.add)
-----------------------------打印结果-----------------------------
信息表
信息表
类函数内调用不带参数的类函数
class People:
age=20
occupation="程序员"
height=180
name="小明"
def cook(self,name="神厨小福贵"):
print("{}他会做粤菜,川菜".format(name))
self.repair() #调用函数repair()
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,name):
self.cook(name) #调用带属性的函数
print("他会修电脑,修电视")
test=People() #创建实例
test.cook("美羊羊") #传入参数
---------------------打印结果---------------------
美羊羊他会做粤菜,川菜
类函数带有动态参数
class People:
age=20
occupation="程序员"
height=180
name="小明"
def cook(self,*args):
for name in args:
print("{}他会做粤菜,川菜".format(name))
test=People() #创建实例
test.cook("张三","李四","王五","喜洋洋","派大星") #传入参数
--------------------------打印结果--------------------------
张三他会做粤菜,川菜
李四他会做粤菜,川菜
王五他会做粤菜,川菜
喜洋洋他会做粤菜,川菜
派大星他会做粤菜,川菜
类函数带有关键字参数
class People:
age=20
occupation="程序员"
height=180
name="小明"
def cook(self,**kwargs):
print("{}他会做粤菜,川菜".format(kwargs))
test=People() #创建实例
test.cook(name="章鱼哥",knife="刀具") #传入参数
-------------------------打印结果-------------------------
{'knife': '刀具', 'name': '章鱼哥'}他会做粤菜,川菜