一、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__

python学习——面对对象进阶的更多相关文章

  1. Python - 面对对象(进阶)

    目录 Python - 面对对象(进阶) 类的成员 一. 字段 二. 方法 三. 属性 类的修饰符 类的特殊成员 Python - 面对对象(进阶) 类的成员 一. 字段 字段包括:普通字段和静态字段 ...

  2. Python学习day13-函数进阶(1)

    Python学习day13-函数进阶(1) 闭包函数 闭包函数,从名字理解,闭即是关闭,也就是说把一个函数整个包起来.正规点说就是指函数内部的函数对外部作用域而非全局作用域的引用. 为函数传参的方式有 ...

  3. 小学生绞尽脑汁也学不会的python(初识面对对象)

    小学生绞尽脑汁也学不会的python(初识面对对象) 一. 面向对象思想 1. 面向过程. 重点在"过程". 按照实物的发展流程. 先干嘛,后干嘛, 最后干嘛.... 优点: 简单 ...

  4. Python学习day15-函数进阶(3)

    figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...

  5. Python学习day14-函数进阶(2)

    figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...

  6. Java学习——面对对象的思想入门

          本文是看过<head first Java>之后的一点感悟,写点东西帮忙以后回忆,Java目前在我的工作中用到还不多,而我又对面对对象的编程非常的感兴趣.曾经在MFC平台上写过 ...

  7. Python学习_01_对象

    之前关于python的知识比较零散,这一个系列的随笔将python重新学习整理一遍.学习书籍<Python核心编程>第二版. Python对象基础 python并不是一个单纯面向对象的语言 ...

  8. 【我要学python】面对对象编程之继承和多态

    class animal(object): def run(): print('animal is running...') class dog(animal): def run(self): pri ...

  9. python学习之对象的三大特性

    在面向对象程序设计中,对象可以看做是数据(特性)以及由一系列可以存取.操作这些数据的方法所组成的集合.编写代码时,我们可以将所有功能都写在一个文件里,这样也是可行的,但是这样不利于代码的维护,你总不希 ...

随机推荐

  1. pt-heartbeat(percona toolkit)

    pt-heartbeat是用来监控主从延迟的一款percona工具,现在我们大部分的MySQL架构还是基于主从复制,例如MHA,MMM,keepalived等解决方案.而主从环境的话,我们很关心的就是 ...

  2. 初看Mybatis 源码 (三) SQL是怎么执行的

    前面说到Java动态代理,Mybatis通过这种方式实现了我们通过getMapper方式得到的Dao接口,可以直接通过接口的没有实现的方法来执行sql. AuthUserDao mapper = se ...

  3. QT的动画效果 抖动 下坠 透明 最近在开发QT收藏了好多链接

    http://blog.csdn.net/liang19890820/article/details/51888114

  4. antd Icon

    引入 : import { Icon } from 'antd'; <Icon type = "home" //图标样式 theme = "filled" ...

  5. INDEX SKIP SCAN适用场景

    --请记住这个INDEX SKIP SCAN扫描方式 drop table t purge;create table t as select * from dba_objects;update t s ...

  6. c++ nested class 嵌套类。

    c++ primer 658页 嵌套类最常用于定义执行类,

  7. 1874 football game(三分法and method to compute the area of trianngle)

    FInd the max area. 1. 三分法 2. NAN (not comparable with number) http://acm.timus.ru/problem.aspx?space ...

  8. python UI自动化实战记录八:添加配置

    添加配置文件写入测试地址等,当环境切换时只需修改配置文件即可. 1 在项目目录下添加文件 config.ini 写入: [Domain] domain = http://test.domain.cn ...

  9. [原]零基础学习视频解码之FFMpeg中比较重要的函数以及数据结构

    在正式开始解码练习前先了解下关于FFmpeg中比较重要的函数以及数据结构. 1. 数据结构:  (1) AVFormatContext  AVFormatContext是一个贯穿始终的数据结构,很多函 ...

  10. D3——动态绑定数据

    一.绑定数组元素 , , , , ]; d3.select("body") .selectAll("p") .data(dataset) .enter() .a ...