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())