python学习——面对对象进阶
一、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学习——面对对象进阶的更多相关文章
- Python - 面对对象(进阶)
目录 Python - 面对对象(进阶) 类的成员 一. 字段 二. 方法 三. 属性 类的修饰符 类的特殊成员 Python - 面对对象(进阶) 类的成员 一. 字段 字段包括:普通字段和静态字段 ...
- Python学习day13-函数进阶(1)
Python学习day13-函数进阶(1) 闭包函数 闭包函数,从名字理解,闭即是关闭,也就是说把一个函数整个包起来.正规点说就是指函数内部的函数对外部作用域而非全局作用域的引用. 为函数传参的方式有 ...
- 小学生绞尽脑汁也学不会的python(初识面对对象)
小学生绞尽脑汁也学不会的python(初识面对对象) 一. 面向对象思想 1. 面向过程. 重点在"过程". 按照实物的发展流程. 先干嘛,后干嘛, 最后干嘛.... 优点: 简单 ...
- Python学习day15-函数进阶(3)
figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...
- Python学习day14-函数进阶(2)
figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...
- Java学习——面对对象的思想入门
本文是看过<head first Java>之后的一点感悟,写点东西帮忙以后回忆,Java目前在我的工作中用到还不多,而我又对面对对象的编程非常的感兴趣.曾经在MFC平台上写过 ...
- Python学习_01_对象
之前关于python的知识比较零散,这一个系列的随笔将python重新学习整理一遍.学习书籍<Python核心编程>第二版. Python对象基础 python并不是一个单纯面向对象的语言 ...
- 【我要学python】面对对象编程之继承和多态
class animal(object): def run(): print('animal is running...') class dog(animal): def run(self): pri ...
- python学习之对象的三大特性
在面向对象程序设计中,对象可以看做是数据(特性)以及由一系列可以存取.操作这些数据的方法所组成的集合.编写代码时,我们可以将所有功能都写在一个文件里,这样也是可行的,但是这样不利于代码的维护,你总不希 ...
随机推荐
- 一道算法题-从1到n整数中1出现的次数
1. 题目描述 输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数.例如输入12,从1到12这些整数中包含1的数字有1,10,11和12,1一共出现了5次. 2. 题目来源 第一次看到是在 ...
- HTTP常用状态码大全
HTTP状态码对照表 HTTP response codes 当浏览者访问一个网页时,浏览者的浏览器会向网页所在服务器发出请求.当浏览器接收并显示网页前,此网页所在的服务器会返回一个包含HTTP状态码 ...
- Oracle Fusion Middleware Supported System check,jdk,java .etc requirements
http://www.oracle.com/technetwork/middleware/ias/downloads/fusion-certification-100350.html 在oracle官 ...
- python UI自动化实战记录五:测试页面2 pageobject
该部分记录测试页面2-StrategyPage,所有页面2上的元素定位.操作.获取属性等方法都写在该类中. 1 页面2继承自BasePage: 2 页面2第一部分写的是所有的定位器 3 页面2第二部分 ...
- char *转string遇到诡异的问题记录
这个问题的背景是在用libevent的buffer_remove时出现的,写一个伪代码 char buffer[2048] ={0}; string str; int n = buffer_remov ...
- 汇编试验四:[bx] 和 loop 的使用
预备知识: 段前缀的使用: ffff:0~ffff:b 和 0020:0~0020:b 的数据: 一次循环的复制效果: 但是,这种方式DS的数据得修改: Source Code: assume cs: ...
- Yii2控制器 返回 json 格式数据
Yii::$app->response->format = Response::FORMAT_JSON; $data = User::find()->where([])->as ...
- Eclipse安装Sonarlint插件
这里安装的是Sonarlint3.6.插件安装非常简单.插件比Sonar更为简单快捷. 一.首先通过点击Eclipse上方Help菜单会出现一个下拉列表,点击其中的Eclipse MarketPlac ...
- 十、IntelliJ IDEA 中 Project 和 Module 的概念及区别
在 IntelliJ IDEA 中,没有类似于 Eclipse 工作空间(Workspace)的概念,而是提出了Project和Module这两个概念.接下来,就让咱们一起看看 IntelliJ ID ...
- 【luogu P3623 [APIO2008]免费道路】 题解
题目链接:https://www.luogu.org/problemnew/show/P3623 说是对克鲁斯卡尔的透彻性理解 正解: 先考虑加入水泥路,然后再考虑加入剩下必须要加入的最少鹅卵石路. ...