一、isinstance和issubclass

  1. class Foo:
  2. pass
  3.  
  4. class Son(Foo):
  5. pass
  6.  
  7. s = Son()
  8. #判断一个对象是不是这个类的对象,传两个参数(对象,类)
  9. # print(isinstance(s,Son))
  10. # print(isinstance(s,Foo))
  11. # print(type(s) is Son)
  12. # print(type(s) is Foo)
  13.  
  14. #判断一个类是不是另一类的子类,传两个参数(子类,父类)
  15. print(issubclass(Son,Foo))
  16. print(issubclass(Son,object))
  17. print(issubclass(Foo,object))
  18. print(issubclass(int,object))

二、反射

python面向对象中的反射:通过字符串的形式操作对象相关的属性。python中的一切事物都是对象(都可以使用反射)

四个方法:hasattr(),getattr(),setattr(),delattr()

1.对象中

  1. def __init__(self,name,age):
  2. self.name=name
  3. self.age=age
  4. def fun(self):
  5. print("...........xander")
  6. f=Foo("xander",23)
  7. print(hasattr(f,"name"))
  8. print(hasattr(f,"age"))
  9. print(hasattr(f,"fun"))
  10. print(getattr(f,"name"))
  11. print(getattr(f,"age"))
  12. print(getattr(f,"fun"))
  13. fu=getattr(f,"fun")
  14. fu()
  15. print("".center(50,"-"))
  16. setattr(f,"name","egon")
  17. setattr(f,"age",73)
  18. print(f.name,f.age)
  19. print("--------------------")
  20. delattr(f,"name")
  21. print(f.name)
  1. True
  2. True
  3. True
  4. ctz
  5. 21
  6. <bound method Foo.fun of <__main__.Foo object at 0x00000000023F9DD8>>
  7. ...........ctz
  8. --------------------------------------------------
  9. egon 73
  10. --------------------
  11. Traceback (most recent call last):
  12. File "G:/test/week6/day27/反射1 对象.py", line 32, in <module>
  13. print(f.name)
  14. AttributeError: 'Foo' object has no attribute 'name'
  1. '''反射'''
  2. class People:
  3. country = 'china'
  4. def __init__(self, name, age):
  5. self.name = name
  6. self.age = age
  7. def talk(self):
  8. print('%s is talking'% self.name)
  9. p = People('xander', 23)
  10. p.talk()
  11. choice = input('>>>:') # 输入的字符串
  12. print(p.choice) # p.'name'
  13.  
  14. hasattr(p, 'name') # 判断p里面有没有p.name,字典中——dict——有没有
  15. hasattr(p, 'talk')
  16.  
  17. print(getattr(p, 'nameqqq', None)) # 取到
  18. print(getattr(p, 'talk', None))
  19. print(getattr(People, 'country')) # 类也一样
  20.  
  21. setattr(p, 'sex', 'male') # p.sex = 'male' 修改,新增
  22. print(p.sex)
  23.  
  24. delattr(p, 'age') # del p.age 删除
  25. print(p.__dict__)

2.类中

  1. __author__ = 'Administrator'
  2. class Foo:
  3. f=123
  4. @staticmethod
  5. def static():
  6. print("static......")
  7.  
  8. @classmethod
  9. def clas(cls):
  10. print(cls.f,"class.............")
  11.  
  12. print(hasattr(Foo,"f"))
  13. print(hasattr(Foo,"static"))
  14. print(hasattr(Foo,"clas"))
  15.  
  16. if hasattr(Foo,"f"):
  17. print(getattr(Foo,"f"))
  18.  
  19. print(getattr(Foo,"static"))
  20. print(getattr(Foo,"clas"))
  21. s=getattr(Foo,"static")
  22. s()
  23. c=getattr(Foo,"clas")
  24. c()
  1. True
  2. True
  3. True
  4. 123
  5. <function Foo.static at 0x000000000241B9D8>
  6. <bound method Foo.clas of <class '__main__.Foo'>>
  7. static......
  8. 123 class.............

3.模块

  1. import my_module
  2. # print(hasattr(my_module,'test'))
  3. # # func_test = getattr(my_module,'test')
  4. # # func_test()
  5. # getattr(my_module,'test')()
  6. #import其他模块应用反射
  7.  
  8. from my_module import test
  9.  
  10. def demo1():
  11. print('demo1')
  12.  
  13. import sys
  14. print(__name__) #'__main__'
  15. print(sys.modules)
  16. #'__main__': <module '__main__' from 'D:/Python代码文件存放目录/S6/day26/6反射3.py'>
  17. module_obj =sys.modules[__name__] #sys.modules['__main__']
  18. # module_obj : <module '__main__' from 'D:/Python代码文件存放目录/S6/day26/6反射3.py'>
  19. print(module_obj)
  20. print(hasattr(module_obj,'demo1'))
  21. getattr(module_obj,'demo1')()
  22. #在本模块中应用反射
  1. __author__ = 'Administrator'
  2. import aa
  3.  
  4. print(hasattr(aa,"bb"))
  5. g=getattr(aa,"bb")
  6. g()
  7.  
  8. def Demo():
  9. print("本模块自己的反射")
  10.  
  11. import sys
  12. print(sys.modules)
  13. module=sys.modules[__name__]
  14. if hasattr(module,"Demo"):
  15. d=getattr(module,"Demo")
  16. d()
  1. def bb():
  2. print("bbbbb")
  3. #aa
  1. '''反射的应用'''
  2. class Service():
  3. def run(self):
  4. while 1:
  5. cd = input('>>>:').strip() # 根据用户输入执行命令
  6. cmds = cd.split(' ')
  7. if hasattr(self, cmds[0]):
  8. func = getattr(self, cmds[0])
  9. func(cmds)
  10. def get(self, cmds):
  11. print('get......', cmds)
  12. def put(self, cmds):
  13. print('put......', cmds)
  14. s = Service()
  15. s.run()

二、内置方法:

__str__和__repr__

改变对象的字符串显示__str__,__repr__

自定制格式化字符串__format__

  1. class Foo:
  2. def __init__(self,name):
  3. self.name = name
  4. def __str__(self):
  5. return '%s obj info in str'%self.name
  6. def __repr__(self):
  7. return 'obj info in repr'
  8.  
  9. f = Foo('egon')
  10. # print(f)
  11. print('%s'%f)
  12. print('%r'%f)
  13. print(repr(f)) # f.__repr__()
  14. print(str(f))
  15. #当打印一个对象的时候,如果实现了str,打印中的返回值
  16. #当str没有被实现的时候,就会调用repr方法
  17. #但是当你用字符串格式化的时候 %s和%r会分别去调用__str__和__repr__
  18. #不管是在字符串格式化的时候还是在打印对象的时候,repr方法都可以作为str方法的替补
  19. #但反之不行
  20. #用于友好的表示对象。如果str和repr方法你只能实现一个:先实现repr
  1. '''__str__方法 print()时运行'''
  2. d = dict({'name': 'xander'})
  3. print(isinstance(d, dict))
  4.  
  5. class People:
  6. def __init__(self, name, age):
  7. self.name = name
  8. self.age = age
  9. def __str__(self):
  10. print('>>>:str')
  11. return '<name:%s,age:%s>' % (self.name, self.age)
  12. p = People('xander', 23)
  13. print(p) # p.__str__()

True
>>>:str
<name:xander,age:23>

  1.  

__del__

析构方法,当对象在内存中被释放时,自动触发执行。

注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给Python解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的。

  1. __author__ = 'Administrator'
  2. class Foo:
  3. def __del__(self):
  4. print("执行我来")
  5.  
  6. f = Foo()
  7. print(123)
  8. print(123)
  9. del f
  10. print(123)
  11. print(123)
  12. print(123)
  1. '''__del__方法(在对象被删除之前,先运行__del__方法)'''
  2. class Open():
  3. def __init__(self, filename):
  4. print('open filename')
  5. self.filename = filename
  6. def __del__(self):
  7. print('填写回收操作系统资源 del......')
  8. a = Open('__init__.py')
  9. del a
  10. a = Open('__init__.py')
  11. print('__main__') # 程序关闭之前,删除对象之前.__del__方法

open filename
填写回收操作系统资源 del......
open filename
__main__
填写回收操作系统资源 del......

item系列

__getitem__\__setitem__\__delitem__

  1. '''item系列 当成字典来操作'''
  2. class Foo:
  3. def __init__(self, name, age):
  4. self.name = name
  5. self.age = age
  6. def __getitem__(self, item):
  7. print('getitem...')
  8. print(self.__dict__[item])
  9. def __setitem__(self, key, value):
  10. print('setitem...')
  11. self.__dict__[key] = value
  12. def __delitem__(self, key):
  13. print('delitem...')
  14. del self.__dict__[key]
  15. f = Foo('xander', 23)
  16. print(f.__dict__)
  17. # 查看属性
  18. f['name']
  19. # 设置属性
  20. f['sex'] = 'boy'
  21. print(f.__dict__)
  22. # 删除属性
  23. del f['sex']
  24. print(f.__dict__)

{'name': 'xander', 'age': 23}
getitem...
xander
setitem...
{'name': 'xander', 'age': 23, 'sex': 'boy'}
delitem...
{'name': 'xander', 'age': 23}

  1. class Foo:
  2. def __init__(self):
  3. self.name = 'egon'
  4. self.age = 73
  5.  
  6. def __getitem__(self, item):
  7. return self.__dict__[item]
  8.  
  9. def __setitem__(self, key, value):
  10. # print(key,value)
  11. self.__dict__[key] = value
  12.  
  13. def __delitem__(self, key):
  14. del self.__dict__[key]
  15. f = Foo()
  16. # f['name'] = 'alex'
  17. # del f['name']
  18. # print(f.name)
  19. f1 = Foo()
  20. print(f == f1)
  21. # print(f[0])
  22. # print(f[1])
  23. # print(f[2])

单例模式

  1. class Singleton:
  2. def __new__(cls, *args, **kw):
  3. if not hasattr(cls, '_instance'):
  4. orig = super(Singleton, cls)
  5. cls._instance = orig.__new__(cls, *args, **kw)
  6. return cls._instance
  7.  
  8. one = Singleton()
  9. two = Singleton()
  10.  
  11. two.a = 3
  12. print(one.a)
  13. # 3
  14. # one和two完全相同,可以用id(), ==, is检测
  15. print(id(one))
  16. # 29097904
  17. print(id(two))
  18. # 29097904
  19. print(one == two)
  20. # True
  21. print(one is two)
  22.  
  23. 单例模式

__call__

对象后面加括号,触发执行。

注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()

  1. class Foo:
  2.  
  3. def __init__(self):
  4. pass
  5.  
  6. def __call__(self, *args, **kwargs):
  7.  
  8. print('__call__')
  9.  
  10. obj = Foo() # 执行 __init__
  11. obj() # 执行 __call__

__len__

  1. class A:
  2. def __init__(self):
  3. self.a = 1
  4. self.b = 2
  5.  
  6. def __len__(self):
  7. return len(self.__dict__)
  8. a = A()
  9. print(len(a))
  1. # class Foo:
  2. # # def __len__(self):
  3. # # return len(self.__dict__)
  4. # def __hash__(self):
  5. # print('my hash func')
  6. # return hash(self.name)
  7. # f = Foo()
  8. # # print(len(f))
  9. # f.name = 'egon'
  10. # # print(len(f))
  11. # print(hash(f))

__hash__

  1. class A:
  2. def __init__(self):
  3. self.a = 1
  4. self.b = 2
  5.  
  6. def __hash__(self):
  7. return hash(str(self.a)+str(self.b))
  8. a = A()
  9. print(hash(a))

__eq__

  1. class A:
  2. def __init__(self):
  3. self.a = 1
  4. self.b = 2
  5.  
  6. def __eq__(self,obj):
  7. if self.a == obj.a and self.b == obj.b:
  8. return True
  9. a = A()
  10. b = A()
  11. print(a == b)

纸牌游戏

  1. class FranchDeck:
  2. ranks = [str(n) for n in range(2,11)] + list('JQKA')
  3. suits = ['红心','方板','梅花','黑桃']
  4.  
  5. def __init__(self):
  6. self._cards = [Card(rank,suit) for rank in FranchDeck.ranks
  7. for suit in FranchDeck.suits]
  8.  
  9. def __len__(self):
  10. return len(self._cards)
  11.  
  12. def __getitem__(self, item):
  13. return self._cards[item]
  14.  
  15. deck = FranchDeck()
  16. print(deck[0])
  17. from random import choice
  18. print(choice(deck))
  19. print(choice(deck))
  20.  
  21. 纸牌游戏

纸牌游戏2

  1. class FranchDeck:
  2. ranks = [str(n) for n in range(2,11)] + list('JQKA')
  3. suits = ['红心','方板','梅花','黑桃']
  4.  
  5. def __init__(self):
  6. self._cards = [Card(rank,suit) for rank in FranchDeck.ranks
  7. for suit in FranchDeck.suits]
  8.  
  9. def __len__(self):
  10. return len(self._cards)
  11.  
  12. def __getitem__(self, item):
  13. return self._cards[item]
  14.  
  15. def __setitem__(self, key, value):
  16. self._cards[key] = value
  17.  
  18. deck = FranchDeck()
  19. print(deck[0])
  20. from random import choice
  21. print(choice(deck))
  22. print(choice(deck))
  23.  
  24. from random import shuffle
  25. shuffle(deck)
  26. print(deck[:5])
  27.  
  28. 纸牌游戏2

面试题

  1. class Person:
  2. def __init__(self,name,age,sex):
  3. self.name = name
  4. self.age = age
  5. self.sex = sex
  6.  
  7. def __hash__(self):
  8. return hash(self.name+self.sex)
  9.  
  10. def __eq__(self, other):
  11. if self.name == other.name and self.sex == other.sex:return True
  12.  
  13. p_lst = []
  14. for i in range(84):
  15. p_lst.append(Person('egon',i,'male'))
  16.  
  17. print(p_lst)
  18. print(set(p_lst))
  19.  
  20. 一道面试题

python 反射和内置方法的更多相关文章

  1. Python反射和内置方法(双下方法)

    Python反射和内置方法(双下方法) 一.反射 什么是反射 反射的概念是由Smith在1982年首次提出的,主要是指程序可以访问.检测和修改它本身状态或行为的一种能力(自省).这一概念的提出很快引发 ...

  2. python 面向对象之反射及内置方法

    面向对象之反射及内置方法 一.静态方法(staticmethod)和类方法(classmethod) 类方法:有个默认参数cls,并且可以直接用类名去调用,可以与类属性交互(也就是可以使用类属性) 静 ...

  3. 面向对象(五)——isinstance与issubclass、反射、内置方法

    isinstance与issubclass.反射.内置方法 一.isinstance与issubclass方法 1.isinstance是用来判断对象是否是某个类 isinstance(obj,cla ...

  4. python常用数据类型内置方法介绍

    熟练掌握python常用数据类型内置方法是每个初学者必须具备的内功. 下面介绍了python常用的集中数据类型及其方法,点开源代码,其中对主要方法都进行了中文注释. 一.整型 a = 100 a.xx ...

  5. python字符串常用内置方法

    python字符串常用内置方法 定义: 字符串是一个有序的字符的集合,用与存储和表示基本的文本信息. python中引号中间包含的就是字符串. # s1='hello world' # s2=&quo ...

  6. python字符串处理内置方法一览表

    python字符串处理内置方法一览表   序号 方法及描述 1 capitalize()将字符串的第一个字符转换为大写 2 center(width, fillchar) 返回一个指定的宽度 widt ...

  7. python面向对象 : 反射和内置方法

    一. 反射 1. isinstance()和issubclass() isinstance( 对象名, 类名) : 判断对象所属关系,包括父类  (注:type(对象名) is 类名 : 判断对象所属 ...

  8. Python之路(第二十五篇) 面向对象初级:反射、内置方法

    [TOC] 一.反射 反射的概念是由Smith在1982年首次提出的,主要是指程序可以访问.检测和修改它本身状态或行为的一种能力(自省).这一概念的提出很快引发了计算机科学领域关于应用反射性的研究.它 ...

  9. 《Python》反射、内置方法(__str__,__repr__)

    一.反射 通过字符串的形式操作对象相关的属性.(使用字符串数据类型的变量名来获取这个变量的值) Python中的一切事物都是对象(都可以使用反射) 反射类中的变量 反射对象中的变量 反射模板中的变量 ...

随机推荐

  1. CENTOS 使用 MUTT发送邮件

    有些时候我们需要在Centos服务器上发送邮件,例如备份MySQL数据库并发送到指定邮箱,这里我们就说下如何从Centos的shell命令发送邮件. 检查.安装.启动sendmail //检查 ps ...

  2. SDN网络工具

    TcpDump 根据使用者的定义对网络上的数据包进行截获的包分析工具. http://www.cnblogs.com/ggjucheng/archive/2012/01/14/2322659.html ...

  3. Java编程规范参考

    谷歌Java编程规范-原版 谷歌Java编程规范-中文翻译版 阿里巴巴Java编程规范 阿里巴巴Java编程规范-IDEA 插件 阿里巴巴Java编程规范-Eclipse 插件

  4. Linux Mint 17 搭建 JSP 环境

    一.配置Tomcat 服务器 1.下载 tomcat 2.解压后放到/usr/local目录下面 3.以root权限执行  chmod +x *.sh 4.启动 ./startup.sh#方式1 ./ ...

  5. Ubuntu14.04下 安装xhprof

    1.下载xhprof包: wget http://pecl.php.net/get/xhprof-0.9.4.tgz 2.解压 进入扩展目录 .tgz cd /home/justphp/xhprof- ...

  6. [GO]简单的并发服务器

    package main import ( "net" "fmt" "strings" ) func HandleConn(conn net ...

  7. 网页渗透-wpscan

    wpscan –url www.xxx.com #扫描基本信息 wpscan –url www.xxx.com –enumerate p #扫描插件基本信息 wpscan –url www.xxx.c ...

  8. ConsoleAppender

    http://logback.qos.ch/manual/appenders.html#ConsoleAppender <configuration> <appender name= ...

  9. telnet ip port

    windows测试远程端口服务是否能连接上:telnet ip port windows7 系统需要手动启用telnet功能,如下图:

  10. Retrofit+Rxjava observable转javabean失败

    报错提示: Caused by: java.lang.IllegalArgumentException: Unable to create call adapter for io.reactivex. ...