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学习之对象的三大特性
在面向对象程序设计中,对象可以看做是数据(特性)以及由一系列可以存取.操作这些数据的方法所组成的集合.编写代码时,我们可以将所有功能都写在一个文件里,这样也是可行的,但是这样不利于代码的维护,你总不希 ...
随机推荐
- 一、docker学习笔记——安装docker
系统win10 企业版 1.下载docker CE 2.安装.注意,由于docker 与Oracle VM VirtualBox 冲突,在windows平台上二者不可共存.你只能2选1!! 3.如果d ...
- SVN安装操作流程
SVN 安装操作流程 1.服务端安装流程 1.1 双击打开svn-server安装包 1.2 点击Next 1.3 勾选上“I accert the terms in the License Agre ...
- TB5上正常使用msfconsole
在TB上使用系统自带的msfconsole,给出以下错误 [-] Failed to connect to the database: could not connect to server: Con ...
- dia无法输入中文的解决
安装dia后无法输入中文,解决如下: 修改/usr/bin/dia #dia-normal --integrated "$@" dia-normal "$@"
- 时间函数应用 time
表 1. C 时间函数 function 定义 含义 返回值 精度 time() time 函数获得从 1970 年 1 月 1 日 0 点到当前的秒数,存储在time_t结构之中. time_t 秒 ...
- Ajax三级联动操作的js代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...
- PowerDNS简单教程(2):功能篇
目录: PowerDNS简单教程(1):安装篇 http://www.cnblogs.com/anpengapple/p/5205130.html PowerDNS简单教程(2):功能篇(本篇) Po ...
- BZOJ3790:神奇项链(Manacher)
Description 母亲节就要到了,小 H 准备送给她一个特殊的项链.这个项链可以看作一个用小写字 母组成的字符串,每个小写字母表示一种颜色.为了制作这个项链,小 H 购买了两个机器.第一个机器可 ...
- Cocos2dx打包apk时变更NDK引发问题及解决
现在官方的Cocos Studio已经支持打包apk文件,写该随笔的时候还没试过官方的打包功能,所以就按自己的学习顺序先把打包的心得写下. 问题及最终解决方案: 其中耗时最长的问题就是ndk-r10改 ...
- 3springboot:springboot配置文件(配置文件、YAML、属性文件值注入<@Value、@ConfigurationProperties、@PropertySource,@ImportResource、@Bean>)
1.配置文件: springboot默认使用一个全局配置文件 配置文件名是固定的 配置文件有两种(开头均是application,主要是文件的后缀): ->application.prope ...