Day18:polymorphic and reflection

1:POLYMORPHIC:

#>>>>>>the Three character of class:inherit;polymorphic;package and cover:
#>>>>>>...1:inherit:change and stretch
#>>>>>>...2:polymorphic:different obj to use the same method:
Day18:polymorphic and reflectionDay18:polymorphic and reflection
 1 # class H20:
 2 #     def __init__(self,name,temprature):
 3 #         self.name = name
 4 #         self.temprature =temprature
 5 #
 6 #     def turn_ice(self):
 7 #         if self.temprature < 0:
 8 #             print('%s is so low'%self.name)
 9 #         elif self.temprature > 0 and self.temprature < 100:
10 #             print('%s is so normal'%self.name)
11 #         if self.temprature > 100:
12 #             print('%s is so high' % self.name)
13 #
14 # class Water(H20):
15 #     pass
16 # class Ice(H20):
17 #     pass
18 # class Steam(H20):
19 #     pass
20 #
21 # w1 = Water('water',50)
22 # i1 = Ice('ice', -20)
23 # s1 = Water('steam', 1000)\
24 # #
25 # # w1.turn_ice()
26 # # i1.turn_ice()
27 # # s1.turn_ice()
28 #
29 # #write a func to include the same method:
30 # def func(obj):
31 #     obj.turn_ice()
32 #
33 # func(w1)
34 # func(i1)
35 # func(s1)
View Code
#>>>>>>...3:package: package the contents in the class
#>>>>>>>>3.1:cover1:when you import you can use the method but do not know the logical
#>>>>>>>>3.2:cover2:use small unserline'_'
Day18:polymorphic and reflectionDay18:polymorphic and reflection
 1 # class People:
 2 #
 3 #     # _start = 'earth'           #can be use outside,out of the module,should't be used out of the module
 4 #     __start = 'earth'            #can be called by _print(p1.People__start)
 5 #     def __init__(self,id,name,age,salary):
 6 #         print('>>>>>>',self.__start)    #put it here can call the __start directly
 7 #         self.id = id
 8 #         self.name = name
 9 #         self.age = age
10 #         self.salary = salary
11 #
12 #     def get_id(self):
13 #         print("the id I find is [%s]"%self.id)
14 #
15 #     # visit(port) function:
16 #     def get_start(self):
17 #         print(self.__start)    #visit function:the function is not hidden so can call the __strt
18 #
19 # p1 = People('500245845439','alex',18,349020)
20 # # print(p1.__dict__)
21 # # print(p1._start )
22 # print(People.__dict__)   #have this :'_People__start': 'earth',
23 # # print(p1._People__start)
24 # p1.get_start()
25 
26 class Room:
27     def __init__(self,name,owner,width,length,height):
28         self.name = name
29         self.owner = owner
30         # self.__width = width        #if the contend is not private,there is no need to hide it
31         # self.__length = length
32         self.width = width
33         self.length = length
34         self.height = height
35     # def tell_area(self):
36     #     return self.__width * self.__length
37 
38 r1 = Room('bathroom','alex',29,30,45)
39 # print(r1.tell_area())
40 # print(r1.__width * r1.__length)    #report wrong
41 print(r1.width * r1.length)
View Code

2:REFLECTION:

#the 4 methods below  used in class and object:
#>>>>>>>>>hasattr(object,name),getattr(object,name,default=None),setattr(x,y,v),delattr(x,y):
Day18:polymorphic and reflectionDay18:polymorphic and reflection
 1 class BlackMedium:
 2     feture = 'Ugly'
 3     def __init__(self,name,addr):
 4         self.name = name
 5         self.addr = addr
 6 
 7     def sell_house(self):
 8         print('[%s] is saling house' % self.name)
 9 
10     def rent_house(self):
11         print('[%s] is renting house' % self.name)
12 
13 b1 = BlackMedium('mingrun','zhongloujie')
14 # print(hasattr(b1,'name'))
15 # print(hasattr(b1,'sell_house'))
16 # print(getattr(b1,'name'))
17 # print(getattr(b1,'rent_house'))
18 # func = getattr(b1,'rent_house')
19 # func()
20 # print(getattr(b1,'dfjadsfjdsfka','no the attribute'))  #no need to write defualt=''
21 # b1.sb = True
22 # setattr(b1,'sb',True)
23 # setattr(b1,'sb1',123)
24 # setattr(b1,'name','SB')
25 # setattr(b1,'func',lambda x:x+1)
26 # setattr(b1,'func1',lambda self:self.name+'sb')
27 # print(b1.func(1))
28 # print(b1.func1(b1))
29 # print(b1.__dict__)
30 # del b1.sb
31 # delattr(b1,'sb1')
32 # print(b1.__dict__)
View Code

3:FTP example:

Day18:polymorphic and reflectionDay18:polymorphic and reflection
 1 class FtpClient:
 2     def __init__(self,addr):
 3         self.addr = addr
 4         print('linking the server[%s]' % self.addr)
 5     def put(self):
 6         print('loading')
 7 ###########################
 8 from ftp_client import FtpClient
 9 f1 = FtpClient('1.1.1.1')
10 # f1.put()
11 if hasattr(f1,'put'):
12     func_get = getattr(f1,'put')
13     func_get()
14 else:
15     print('other logical')
View Code

4:IMPORT module:

Day18:polymorphic and reflectionDay18:polymorphic and reflection
 1 # from m1 import t
 2 module_t = __import__('m1.t')
 3 print(module_t)           #>>>>>>m1
 4 module_t.t.test1()
 5 
 6 import importlib
 7 importlib.import_module('m1.t')   #>>>>>>m1.t
 8 
 9 # m = __import__('dic')
10 # print(m)
11 # from m1.t import *
12 # from m1.t import test1,_test2
13 # test1()
14 # # test2()
15 # _test2()
View Code

5:PACKAGE the content:

Day18:polymorphic and reflectionDay18:polymorphic and reflection
 1 class List(list):
 2     def append(self,p_object):
 3         if type(p_object) is str:
 4             super().append(p_object)
 5         else:
 6             print('must be str')
 7 
 8     def show_middle(self):
 9         mid_index = int(len(self)/2)
10         return self[mid_index]
11 
12 l1 = List('helloworld')
13 # l2 = list('hello world')
14 # print(l1,type(l1))
15 # print(l2,type(l2))
16 # print(l1.show_middle())
17 # l1.append(11111111)
18 l1.append('SB')
19 print(l1)
View Code

6:UNDERLINE __***attr__ method:

Day18:polymorphic and reflectionDay18:polymorphic and reflection
 1 # class Foo:
 2 #     x=1
 3 #     def __init__(self,y):
 4 #         self.y = y
 5 #
 6 #     # def __getattr__(self, item):
 7 #     #     print('excuting __getttr__')
 8 #
 9 #     def __delattr__(self, item):
10 #         del self.item  #infinite recursion
11 #           self.__dict__.pop(item)
12 #         print('deleting __getttr__')
13 #
14 #     def __setattr__(self, key, value):
15 #         print('deleting __setattr__')
16 #         # self.key = value   #infinite recursion
17 #         self.__dict__[key] = value
18 #
19 # f1 = Foo(10)
20 # print(f1.__dict__)
21 # f1.z = 2     #>>>>>trigur __setattr__
22 # print(f1.__dict__)
23 # del f1.y
24 
25 # print(f1.y)
26 # print(getattr(f1,'y'))
27 # f1.ssssssssssss     #>>>>>>>>>>>>excuting __getttr__
28 
29 # class Foo:
30 #     def __getattr__(self, item):
31 #         print('------->>')
32 # print(Foo.__dict__)
33 # print(dir(Foo))
34 # f1=Foo()
35 # print(f1.x)  #>>>>>>when the attribute not exist,trigur the __getattr__
36 
37 
38 class Foo:
39     def __init__(self,name):
40         self.name = name      #trigure __setattr__
41     def __getattr__(self, item):
42         print('the attribute you find is not exist %s' %item)
43 
44     def __setattr__(self, k, v):
45         print('excute __setattr__',k,v)
46         if type(v) is str:
47             print('start setting')
48             # self.k = v  #trigure __setattr__
49             # self.__dict__[k]=v
50             self.__dict__[k] = v.upper()
51         else:
52             print('must be str')
53     def __delattr__(self, item):
54         print('no qulification to delet %s' %item)
55 
56 
57 
58 f1 = Foo('alex')
59 f1.age = 18     #trigure __setattr__
60 # f1.gender = 'male'
61 print(f1.__dict__)
62 #--------------->>:print
63 # excute __setattr__ name alex
64 # excute __setattr__ age 18
65 # excute __setattr__ gender male
66 # {}
67 
68 # print(f1.name)
69 # print(f1.age)
70 del f1.name
View Code

7:AUTHORIZE:

Day18:polymorphic and reflectionDay18:polymorphic and reflection
 1 import time
 2 class Open:
 3     def __init__(self,filename,mode='r',encoding='utf-8'):
 4         # self.filename = filename
 5         self.file = open(filename,mode,encoding=encoding)
 6         self.mode = mode
 7         self.encoding = encoding
 8 
 9     # def read(self):
10     #     pass
11     def write(self,line):
12         print('------>>')
13         t = time.strftime('%Y-%m-%d %X')
14         self.file.write('%s %s\n' %(t,line))
15 
16     def __getattr__(self, item):    #used for the error
17         # print(item,type(item))  #read #str
18         # self.file.read
19         return getattr(self.file,item)
20 
21 # f1 = Open('a1.txt','w')
22 # print(f1.file)
23 f1 = Open('a1.txt','r+')
24 # f1.read  #trigure __getattr__
25 f1.write('111111111111')
26 f1.write('heavy cpu loding')
27 f1.write('low memory capacity')
28 f1.write('low disk capacity')
29 # print(f1.read())
30 
31 # print(f1.seek(4))
32 print(f1.seek(0))
33 print(f1.read())
34 
35 # the result:
36 # 2020-04-21 19:28:36 111111111111
37 # 2020-04-21 19:28:36 heavy cpu loding
38 # 2020-04-21 19:28:36 low memory capacity
39 # 2020-04-21 19:28:36 low disk capacity
View Code

 

上一篇:在线教育项目-day18【权限控制】


下一篇:Python入门day18——迭代器生成器