-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathday4_lab1.py
More file actions
65 lines (54 loc) · 1.94 KB
/
Copy pathday4_lab1.py
File metadata and controls
65 lines (54 loc) · 1.94 KB
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
class Example:
"""add class methods to your class which keeps track of all the instance names which have been created
allnames() should return a list of all the names of objects which exist
count() should return the number of objects that have ever been created
we will need __del__ to accomplish this
"""
__some_data = 'blah'
__how_many = 0
__instance_names = []
__ever_created = 0
def __init__(self, val):
print('in init for Example')
self.name = val # instance data
self.__class__.__how_many += 1 # get from object to class
self.__class__.__ever_created += 1 # get from object to class
self.__class__.__instance_names.append(val)
print('__how_many =', self.__class__.__how_many)
def __del__(self):
self.__class__.__instance_names.remove(self.name)
self.__class__.__how_many -= 1
# We can use a static (or class) method to get around
# a brittle __init__ that doesn't quite do what we want.
@staticmethod
def list_init(somelist):
'''allow me to send in a list, and "flatten" it
into a string with intervening commas'''
obj = Example('')
obj.name = ', '.join(somelist)
return obj
@classmethod
def get_some_data(cls):
return cls.__some_data
@classmethod
def allnames(cls):
return cls.__instance_names
@classmethod
def count_current(cls):
return cls.__how_many
@classmethod
def count_ever(cls):
return cls.__ever_created
if __name__ == '__main__':
print("put tests here to make sure I did the lab right.")
ex1 = Example('example1')
ex2 = Example('example2')
print(Example.allnames())
print(ex2.count_current())
ex3 = Example('example3')
print(ex3.count_current())
print(ex3.count_ever())
del ex3
print(Example.count_current())
print(Example.count_ever())
print(ex1.allnames())