码迷,mamicode.com
首页 > 其他好文 > 详细

Day8 面向对象反射

时间:2017-08-23 20:06:30      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:div   命令   foo   strip   blog   删除   通过   self   while   

反射:通过字符串来访问到所对应的值(反射到真实的属性上)。

eg:

 1 class Foo:
 2     x=1
 3     def __init__(self,name):
 4         self.name=name
 5 
 6     def f1(self):
 7         print(from f1)
 8 
 9 
10 # print(Foo.x) #Foo.__dict__[‘x‘]
11 
12 f=Foo(egon)
13 # print(f.__dict__)
14 #
15 # #1:
16 # print(f.name)
17 
18 #2:
19 # print(f.__dict__[‘name‘])
20 
21 #hasattr
22 #反射到字典所对应的值
23 # print(hasattr(f,‘name‘)) #f.name
24 # print(hasattr(f,‘f1‘)) #f.f1
25 # print(hasattr(f,‘x‘)) #f.x
26 
27 
28 #setattr   
29 #设置某个属性
30 # setattr(f,‘age‘,18)#f.age=18
31 
32 #getattr
33 #得到某个属性的值
34 # print(getattr(f,‘name‘))#f.name
35 # print(getattr(f,‘abc‘,None))#f.abc
36 # print(getattr(f,‘name‘,None))#f.abc
37 
38 # func=getattr(f,‘f1‘)#f.f1
39 # print(func)
40 # func()
41 #
42 
43 #delattr
44 #删除某个属性的值
45 # delattr(f,‘name‘)# del f.name
46 # print(f.__dict__)

 

定义某个功能,输入某条命令,打印下面的功能:

class Ftpserver:
    def __init__(self,host,port):
        self.host=host
        self.port=port

    def run(self):
        while True:
            cmd=input(>>: ).strip()
            if not cmd:continue
            if hasattr(self,cmd):
                func=getattr(self,cmd)
                func()
    def get(self):
        print(get func)

    def put(self):
        print(put func)

 

Day8 面向对象反射

标签:div   命令   foo   strip   blog   删除   通过   self   while   

原文地址:http://www.cnblogs.com/sexiaoshuai/p/7419775.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!