• 类的属性--组合


    组合:组合指的是,在一个类中以另外一个类的对象作为数据属性,称为类的组合----通俗的讲就是什么里面有什么。

    class Weapon:
        def prick(self, obj):  # 这是该装备的主动技能,扎死对方
            obj.life_value -= 500  # 假设攻击力是500
    
    class Person:  # 定义一个人类
        role = 'person'  # 人的角色属性都是人
    
        def __init__(self, name):
            self.name = name  # 每一个角色都有自己的昵称;
            self.weapon = Weapon()  # 给角色绑定一个武器;
            
    egg = Person('egon')
    egg.weapon.prick() 
    装备武器

    组合的应用一般有3中方法:

    1,直接调用,这个要考虑到Circle类里的东西,如果Circle类里面有2个元素,那么__init__(self)里面就要再多加2个元素,并且2个元素名要与Circle元素名一样。

        def __init__(self,radius_outside,radius_inside):
            self.outsid_circle = Circle(radius_outside)
            self.inside_circle = Circle(radius_inside)
    2,是在实例化的时候调用,把里面的元素整个替换为之前的类名,当然这里还是要去类名里面全部的元素。
    class BirthDate:
        def __init__(self,year,month,day):
            self.year=year
            self.month=month
            self.day=day
    
    class Couse:
        def __init__(self,name,price,period):
            self.name=name
            self.price=price
            self.period=period
    
    class Teacher:
        def __init__(self,name,gender,birth,course):
            self.name=name 
            self.gender=gender
            self.birth=birth
            self.course=course
        def teach(self): 
            print('teaching')
    
    p1=Teacher('egon','male', 
                BirthDate('1995','1','27'), 
                Couse('python','28000','4 months')
               ) 
    
    print(p1.birth.year,p1.birth.month,p1.birth.day) 
    
    print(p1.course.name,p1.course.price,p1.course.period)
    ''' 
    运行结果: 
    1 27 
    python 28000 4 months 



    3,直接在类名里面就用。
    class
    Cource: def __init__(self,name,perid,money): self.name =name self.perid=perid self.money=money class Bir: def __init__(self,y,m,d): self.y=y self.m=m self.d=d class Teacher: def __init__(self,name,age,y,m,d): self.name =name self.age=age self.birth=Bir(y,m,d) egg=Teacher("egon",73,1995,12,16) print(egg.name ) print(egg.birth.y)
  • 相关阅读:
    (转)PHP函数之error_reporting(E_ALL ^ E_NOTICE)详细说明
    Java 异步转同步 ListenableFuture in Guava
    makepy
    Eclipse安装Freemarker插件
    Windows下Go语言LiteIDE下载及安装
    Windows 平台下 Go 语言的安装和环境变量设置
    phpcms v9表单向导添加验证码
    mac下谷歌chrome浏览器的快捷键
    vscode的go插件安装
    golang查看文档
  • 原文地址:https://www.cnblogs.com/52forjie/p/7361415.html
Copyright © 2020-2023  润新知