【python学习】面向对象,类与对象-22

类函数不带任何参数

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关键字)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值