• python实例属性,类属性,实例名,和类名的传递


    python的实例属性的传递

    class School:
        def __init__(self, address):
            self.address = address
    
    bj = School('北京总部')
    sh = School('上海分部')
    sz = School('深圳分部')
    
    class Course(object):
        def __init__(self, name, period, price, school=None):         ##只使用类的初始化构造方法,来初始化实例变量
            self.name = name
            self.period = period
            self.price = price
            self.school = school
    
    py1 = Course('Python', 110, 19999, bj)                         #用到的是实例属性的传递
    py2 = Course('Python', 110, 19999, sh)
    py3 = Course('Python', 110, 19999, sz)
    
    l1 = Course('Linux', 110, 19999, bj)
    l2 = Course('Linux', 110, 19999, sh)
    
    g1 = Course('Go开发', 119, 19999, bj)
    
    class Grade(object):
        def __init__(self, name, people, introduce, course=None):
            self.name = name
            self.people = people
            self.introduce = introduce
            self.course = course
    
    gr1 = Grade('全栈1期',20,'....',py1)
    gr2 = Grade('全栈1期',20,'....',py2)
    gr3 = Grade('Linux8期',20,'....',l2)
    
    
    # gr1.people
    # gr1.course.price
    # gr1.course.school.address
    print(gr1.people)
    print(gr1.course.price)
    print(gr1.course.school.address)

    只用类的初始化构造方法来创建实例属性(也可以叫实例变量),在后面可以像变量一样进行自由传递

    类名/实例名 的传递

    class Foo(object):
    
        def __init__(self,age):
            self.age = age
    
        def display(self):
            print(self.age)
    
    data_list = [Foo(8),Foo(9)]   #类名的传递,加括号实际上就成了实例名了
    for item in data_list:
        print(item.display())
    
    obj1=Foo(8)
    print(obj1.display())
  • 相关阅读:
    springBoot从入门到源码分析
    MQ疑难杂症小记
    dubbo学习思路梳理
    Zookeeper
    分布式系统理论概述
    mysql,存储引擎,事务,锁,慢查询,执行计划分析,sql优化
    tomcat学习步骤,附带打破双亲委派模型企业应用实战
    使用UtraISO为U盘制作系统启动盘
    洛谷P3369 splay或treap
    gym 101982 B题 Coprime Integers
  • 原文地址:https://www.cnblogs.com/zhuhaofeng/p/9555173.html
Copyright © 2020-2023  润新知