类关系/self/特殊成员

1.依赖关系
  在方法中引入另一个类的对象
2.关联关系、聚合关系、组合关系

#废话少说 直接上代码===>选课系统

 1 # coding:utf-8
 2 
 3 
 4 class Student(object):
 5     def __init__(self, sid, name, addr):
 6         self.sid = sid
 7         self.name = name
 8         self.addr = addr
 9         self.course = []
10 
11     def get_info(self):
12         for el in self.course:
13             print(el.cid, el.title, el.teacher.tid,
14                   el.teacher.name,el.teacher.phone)
15 
16     def add_course(self, course):
17         self.course.append(course)
18 
19 
20 class Course(object):
21     def __init__(self, cid, title):
22         self.cid = cid
23         self.title = title
24         self.course_list = []
25         self.teacher = ''
26 
27     def get_info(self, course):
28         pass
29 
30     def setting_teacher(self, teacher):
31         self.teacher = teacher
32 
33 
34 class Teacher(object):
35     def __init__(self, tid, name, phone):
36         self.tid = tid
37         self.name = name
38         self.phone = phone
39 
40 
41 t1 = Teacher(11, "张三", 1815786)
42 t2 = Teacher(22, "李四", 10086)
43 
44 c1 = Course(1, "python1")
45 c1.setting_teacher(t1)
46 c2 = Course(2, "python2")
47 c2.setting_teacher(t2)
48 c3 = Course(3, "python3")
49 c3.setting_teacher(t1)
50 s1 = Student(111, "alex", "北京")
51 s1.add_course(c1)
52 s1.add_course(c2)
53 s1.add_course(c3)
54 s1.get_info()
View Code

3.继承关系,实现关系
  #可哈希:内部是否有哈希算法
  __hash__
  默认的类和对象都是可哈希的
  self就是你访问方法的那个对象. 先找自己, 然后在找父类的.

废话少说 上代码

 1 class Base:
 2     def __init__(self, num):
 3         self.num = num
 4 
 5     def func1(self):
 6         print(self.num)
 7         self.func2()
 8 
 9     def func2(self):
10         print(111, self.num)
11 
12 
13 class Foo(Base):
14     def func2(self):
15         print(222, self.num)
16 
17 
18 # Base(1) 1 111 1
19 # Base(2) 2 111 2
20 # Foo(3)  3 222 3
21 # 这里面注意换行
22 lst = [Base(1), Base(2), Foo(3)]
23 for obj in lst:
24     obj.func1()  # 那笔来吧. 好好算.
View Code

4.特殊成员(__init__())
  即带双下划线的
  1.类名() __init__构造方法
  2.对象() __call__() python 特有的

原文地址:https://www.cnblogs.com/d9e84208/p/10595685.html