一、isinstance和issubclass

  isinstance(obj,cls)检查是否obj是否是类 cls 的对象

 class Foo:
pass a = Foo()
print(isinstance(Foo,object)) # 输出:True class Parent(object):
pass b = Parent()
print(isinstance(Parent,object)) # 输出:True

  由此可以看出,python3中若没有说明继承的是哪个类的时候,默认继承object。

  issubclass(sub, super)检查sub类是否是 super 类的派生类

class Parent():
pass class Son(Parent):
pass print(issubclass(Parent,object))
print(issubclass(Son,Parent)) # 输出:
True
True

二、反射

  1、什么是反射(非常强大,也很重要)

    反射的概念是由Smith在1982年首次提出的,主要是指程序可以访问、检测和修改它本身状态或行为的一种能力(自省)。这一概念的提出很快引发了计算机科学领域关于应用反射性的研究。它首先被程序语言的设计领域所采用,并在Lisp和面向对象方面取得了成绩。

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

    四个可以实现自省的函数

    下列方法适用于类和对象(一切皆对象,类本身也是一个对象)

 def hasattr(*args, **kwargs): # real signature unknown
"""
Return whether the object has an attribute with the given name. This is done by calling getattr(obj, name) and catching AttributeError.
"""
pass

hasattr

 def getattr(object, name, default=None): # known special case of getattr
"""
getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
"""
pass

getattr

 def setattr(x, y, v): # real signature unknown; restored from __doc__
"""
Sets the named attribute on the given object to the specified value. setattr(x, 'y', v) is equivalent to ``x.y = v''
"""
pass

setattr

 def delattr(x, y): # real signature unknown; restored from __doc__
"""
Deletes the named attribute from the given object. delattr(x, 'y') is equivalent to ``del x.y''
"""
pass

delattr

 class Parent():
p = '类的静态变量'
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex def say_hello(self):
return '{}say {}'.format(self.name,'hello') obj = Parent('周曾吕',88,'不详') # 检测是否含有某个属性
print(hasattr(obj,'name'))
print(hasattr(obj,'age'))
print(hasattr(obj,'sex'))
print(hasattr(obj,'say_hello')) # 输出:
True
True
True
True # 获取属性
n1 = getattr(obj,'name')
n2 = getattr(obj,'age')
n3 = getattr(obj,'sex') print(n1,n2,n3) # 输出:周曾吕 88 不详 func = getattr(obj,'say_hello')
print(func) # 输出:
<bound method Parent.say_hello of <__main__.Parent object at 0x00000222F34B2CF8>> # print(getattr(obj,'aaaa','不存在')) # 不存在 报错 # 设置属性(赋值)
setattr(obj,'sb',True)
setattr(obj,'show_name',lambda self:self.name + 'sb')
print(obj.__dict__)
print(obj.show_name(obj)) # 输出:
{'name': '周曾吕', 'age': 88, 'sex': '不详', 'sb': True, 'show_name': <function <lambda> at 0x00000222F34CD730>}
周曾吕sb # 删除属性
delattr(obj,'sex')
delattr(obj,'show_name')
delattr(obj,'sb')
# delattr(obj,'show_name_aaa') # 不存在就报错 print(obj.__dict__) # 输出:
{'name': '周曾吕', 'age': 88}

hasattr,getattr,setattr,delattr四个方法的演示

 class Foo:

     staticName = 'University Guiyang'

     def __init__(self):
self.name = 'liulonghai' def func(self):
return 'in func now ' @staticmethod
def qqxing():
return 'qqxing' print(getattr(Foo,'staticName'))
print(getattr(Foo,'func'))
print(getattr(Foo,'qqxing')) ret1 = getattr(Foo,'func')
ret2 = getattr(Foo,'qqxing') print(ret1(Foo))
print(ret2()) # 输出:
University Guiyang
<function Foo.func at 0x0000020D5570E8C8>
<function Foo.qqxing at 0x0000020D5570E950>
in func now
qqxing

类也是对象

  注意:当调用类里面的普通方法时,要传一个类名作为参数,否则会报错。如上面的 ret2(Foo)

 import sys

 n1 = 'qqxing'
def func1():
return 'in func1 now' n2 = 'wahaha'
def func2():
return 'in func2 now' the_module = sys.modules[__name__] if hasattr(the_module,'func1'):
ret1 = getattr(the_module,'func1')
print(ret1())
if hasattr(the_module,'func2'):
ret2 = getattr(the_module,'func2')
print(ret2()) print(getattr(the_module,'n1'))
print(getattr(the_module,'n2')) # 输出:
in func1 now
in func2 now
qqxing
wahaha

反射当前模块成员或者函数

  注意:不管是函数还是变量,反射的时候只能有一个变量,且变量必须是全局变量。

  导入其他模块,可以利用反射来运行该模块中存在的方法

 import 面向对象的三大特性

 if hasattr(面向对象的三大特性,'A'):
ret1 = getattr(面向对象的三大特性,'A')
print(ret1)
print(ret1()) # 输出:
<class '面向对象的三大特性.A'>
China

导入其他模块,利用反射来运行该模块中成员

  注意,若导入的模块是一个类而不是函数,运行的时候可能会报错,他会说这个类的类名不可调用,是因为这个类中没有__call__这个方法,如果你加上之后就不会报错了,但是他返回的是一个内存地址,没有显示这个函数的结果(不管你怎么调用都不显示,而且不会报错,是不是懵逼了),其实是因为类中没有实现__repr__或者__str__这两个双下方法中的其中一个,你加上就可以了。。。

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

  自定制如下的格式化字符串__format__

最新文章

  1. 解决子元素设置margin-top,效果到父元素上的问题
  2. PHP &quot;万能&quot;输出随机字符串
  3. apply 伴生对象 单例对象
  4. [leetcode 37]sudoku solver
  5. iOS开发小技巧--高斯模糊框架的应用
  6. highcharts与highstock实例
  7. JDBC增删改查
  8. 【转】android cts测试方法及步骤
  9. Linux系统的命令别名功能
  10. 泛泰A870L/K/S第三版官方4.4.2原来的系统卡刷机包 (愿自己主动ROOT)
  11. Topcoder SRM 628 DIV 2
  12. HTML5常用标签分类
  13. Django框架之虚拟环境搭建
  14. HBase Region级别二级索引
  15. 20145338 《网络对抗》 MSF基础应用
  16. centos 7 上Hive-2.1.1的安装与基本操作
  17. Python股票分析系列——基础股票数据操作(一).p3
  18. [Oracle][Partition][Controlfile]Partition 操作是否和 Controlfile有关?
  19. Oracle ORA-00911: 无效字符
  20. logistic回归梯度上升优化算法

热门文章

  1. 这么多小程序,会微信小程序就够了
  2. 【Leetcode】【Medium】3Sum
  3. js函数 标签: javascript 2016-08-12 16:48 56人阅读 评论(0) 收藏
  4. 【zz】史上最全设计模式导学目录(完整版)
  5. 在一个Excel单元格内输入多行内容
  6. ThreadLocal介绍
  7. MySQL错误问题
  8. 如何访问tomcat所在服务器的其他盘符的资源。
  9. 牛客网多校训练第三场 C - Shuffle Cards(Splay / rope)
  10. 2018 Multi-University Training Contest 4 Problem B. Harvest of Apples 【莫队+排列组合+逆元预处理技巧】