【python学习】面向对象,属性与方法-23

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': '章鱼哥'}他会做粤菜,川菜

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值