-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass_test.py
99 lines (70 loc) · 1.78 KB
/
class_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
class Animal(object):
def __init__(self):
pass
def speak(self):
print("animal speak")
class Dog(Animal):
def __init__(self):
pass
def speak(self):
print("dog speak")
class Cat(Animal):
def __init__(self):
pass
def speak(self):
print("cat speak")
def speak(animal=Animal()):
animal.speak()
speak(Dog())
speak(Cat())
speak()
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def set_email(self, email):
self.email = email
def do_print(self):
if hasattr(self, 'email'):
print(self.name, self.age, self.email)
else:
print(self.name, self.age)
class Classes(object):
def __init__(self, name):
self.name = name
self.person_list = []
def set_person(self, person):
self.person_list.append(person)
def get_person(self, name):
result = None
for item in self.person_list:
if item.name == name:
result = item
break
return result
def _print(self):
for item in self.person_list:
item.do_print()
c = Classes("one")
c.set_person(person=Person("zhang", 30))
c.set_person(person=Person("lisi", 20))
c.set_person(person=Person("wang", 40))
c.set_person(person=Person("zhao", 60))
lisi = c.get_person("lisi")
lisi.set_email("[email protected]")
print("-----------------")
c._print()
print("-----------------")
# self and cls
class A(object):
class_attr = "class_a"
@classmethod
def set_class_method(cls, class_attr):
cls.class_attr = class_attr
a = A()
b = A()
a.class_attr = 'class_1'
a.set_class_method('class_2')
#a.class_attr = 'class_1'
print(a.class_attr)
print(b.class_attr)