- ubuntu12.04环境下使用kvm ioctl接口实现最简单的虚拟机
- Ubuntu 通过无线网络安装Ubuntu Server启动系统后连接无线网络的方法
- 在Ubuntu上搭建网桥的方法
- ubuntu 虚拟机上网方式及相关配置详解
CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.
这篇CFSDN的博客文章深入浅析Python获取对象信息的函数type()、isinstance()、dir()由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.
type()函数:
使用type()函数可以判断对象的类型,如果一个变量指向了函数或类,也可以用type判断.
如:
1
2
3
4
5
6
7
8
|
class
student(
object
):
name
=
'student'
a
=
student()
print
(
type
(
123
))
print
(
type
(
'abc'
))
print
(
type
(none))
print
(
type
(
abs
))
print
(
type
(a))
|
运行截图如下:
可以看到返回的是对象的类型.
我们可以在if语句中判断比较两个变量的type类型是否相同.
如:
1
2
3
4
5
|
class
student(
object
):
name
=
'student'
a
=
student()
if
type
(
123
)
=
=
type
(
456
):
print
(
"true"
)
|
输出结果为true.
如果要判断一个对象是否是函数怎么办?
我们可以使用types模块中定义的常量。types模块中提供了四个常量types.functiontype、types.builtinfunctiontype、types.lambdatype、types.generatortype,分别代表函数、内建函数、匿名函数、生成器类型.
1
2
3
4
5
6
7
|
import
types
def
fn():
pass
print
(
type
(fn)
=
=
types.functiontype)
print
(
type
(
abs
)
=
=
types.builtinfunctiontype)
print
(
type
(
lambda
x: x)
=
=
types.lambdatype)
print
(
type
((x
for
x
in
range
(
10
)))
=
=
types.generatortype)
|
isinstance()函数:
对于有继承关系的类,我们要判断该类的类型,可以使用isinstance()函数.
如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class
animal(
object
):
def
run(
self
):
print
(
"动物在跑"
)
class
dog(animal):
def
eat(
self
):
print
(
"狗在吃"
)
class
cat(animal):
def
run(
self
):
print
(
"猫在跑"
)
dog1
=
dog()
cat1
=
cat()
print
(
isinstance
(dog1, dog))
print
(
isinstance
(cat1, cat))
print
(
isinstance
(cat1, animal))
print
(
isinstance
(dog1, animal))
|
运行截图如下:
可以看到子类的实例不仅是子类的类型,也是继承的父类的类型.
也就是说,isinstance()判断的是一个对象是否是该类型本身,或者位于该类型的父继承链上.
能用type()判断的基本类型也可以用isinstance()判断,并且还可以判断一个变量是否是某些类型中的一种.
如:
1
2
3
4
5
|
print
(
isinstance
(
'a'
,
str
))
print
(
isinstance
(
123
,
int
))
print
(
isinstance
(b
'a'
, bytes))
print
(
isinstance
([
1
,
2
,
3
], (
list
,
tuple
)))
print
(
isinstance
((
1
,
2
,
3
), (
list
,
tuple
)))
|
运行截图如下:
一般情况下,在判断时,我们优先使用isinstance()判断类型.
dir()函数:
如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list.
如,获得一个str对象的所有属性和方法:
print(dir('abc')) 。
运行结果:
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] 。
类似__xxx__的属性和方法在python中都是有特殊用途的。如在python中,如果你调用len()函数试图获取一个对象的长度,实际上,在len()函数内部,它自动去调用该对象的__len__()方法,因此下面的代码是等价的:
1
2
|
print
(
len
(
'abc'
))
print
(
'abc'
.__len__())
|
运行截图如下:
我们也可以给自己定义的类写一个__len__()方法.
如:
1
2
3
4
5
|
class
mydog(
object
):
def
__len__(
self
):
return
100
dog1
=
mydog()
print
(
len
(dog1))
|
运行截图如下:
前后没有__的都是普通属性或方法.
我们还可以使用getattr()函数获取属性,setattr()函数设置属性,hasattr()函数查找是否具有某属性.
如:
1
2
3
4
5
6
7
8
9
10
11
|
class
myobject(
object
):
def
__init__(
self
):
self
.x
=
9
def
power(
self
):
return
self
.x
*
self
.x
obj1
=
myobject()
print
(
hasattr
(obj1,
'x'
))
print
(
hasattr
(obj1,
'y'
))
setattr
(obj1,
'y'
,
19
)
print
(
hasattr
(obj1,
'y'
))
print
(
getattr
(obj1,
'y'
))
|
运行截图如下:
如果试图获取不存在的属性,会抛出attributeerror的错误。我们可以传入一个default参数,如果属性不存在,就返回默认值.
getattr()函数、setattr()函数、hasattr()函数也可以用于获得、设置、查找对象的方法.
如:
1
2
3
4
5
6
7
8
9
10
11
|
class
myobject(
object
):
def
__init__(
self
):
self
.x
=
9
def
power(
self
):
return
self
.x
*
self
.x
obj1
=
myobject()
print
(
hasattr
(obj1,
'power'
))
print
(
getattr
(obj1,
'power'
))
fn
=
getattr
(obj1,
'power'
)
print
(fn())
|
运行截图如下:
可以看到调用fn()的结果与调用obj1.power()的结果是一样的.
总结:
通过内置的一系列函数,我们可以对任意一个python对象进行剖析,拿到其内部的数据.
要注意的是,只有在不知道对象信息的时候,我们才会去获取对象信息.
如:
1
2
3
4
|
def
readimage(fp):
if
hasattr
(fp,
'read'
):
return
readdata(fp)
return
none
|
假设我们希望从文件流fp中读取图像,我们首先要判断该fp对象是否存在read方法,如果存在,则该对象是一个流,如果不存在,则无法读取。这样hasattr()就派上了用场.
在python这类动态语言中,根据鸭子类型,有read()方法,不代表该fp对象就是一个文件流,它也可能是网络流,也可能是内存中的一个字节流,但只要read()方法返回的是有效的图像数据,就不影响读取图像的功能.
以上所述是小编给大家介绍的python获取对象信息的函数type()、isinstance()、dir(),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我网站的支持! 。
原文链接:https://blog.csdn.net/zgcr654321/article/details/82731116 。
最后此篇关于深入浅析Python获取对象信息的函数type()、isinstance()、dir()的文章就讲到这里了,如果你想了解更多关于深入浅析Python获取对象信息的函数type()、isinstance()、dir()的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
我需要您在以下方面提供帮助。近一个月来,我一直在阅读有关任务和异步的内容。 我想尝试在一个简单的 wep api 项目中实现我新获得的知识。我有以下方法,并且它们都按预期工作: public Htt
我的可执行 jar 中有一个模板文件 (.xls)。不需要在运行时我需要为这个文件创建 100 多个副本(稍后将唯一地附加)。用于获取 jar 文件中的资源 (template.xls)。我正在使用
我在查看网站的模型代码时对原型(prototype)有疑问。我知道这对 Javascript 中的继承很有用。 在这个例子中... define([], function () { "use
影响我性能的前三项操作是: 获取滚动条 获取偏移高度 Ext.getStyle 为了解释我的应用程序中发生了什么:我有一个网格,其中有一列在每个单元格中呈现网格。当我几乎对网格的内容做任何事情时,它运
我正在使用以下函数来获取 URL 参数。 function gup(name, url) { name = name.replace(/[\[]/, '\\\[').replace(/[\]]/,
我最近一直在使用 sysctl 来做很多事情,现在我使用 HW_MACHINE_ARCH 变量。我正在使用以下代码。请注意,当我尝试获取其他变量 HW_MACHINE 时,此代码可以完美运行。我还认为
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 关闭 9 年前。 要求提供代码的问题必须表现出对所解决问题的最低限度的理解。包括尝试过的解决方案、为什么
由于使用 main-bower-files 作为使用 Gulp 的编译任务的一部分,我无法使用 node_modules 中的 webpack 来require 模块code> dir 因为我会弄乱当
关闭。这个问题需要更多focused .它目前不接受答案。 想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post . 关闭 5 年前。 Improve this qu
我使用 Gridlayout 在一行中放置 4 个元素。首先,我有一个 JPanel,一切正常。对于行数变大并且我必须能够向下滚动的情况,我对其进行了一些更改。现在我的 JPanel 上添加了一个 J
由于以下原因,我想将 VolumeId 的值保存在变量中: #!/usr/bin/env python import boto3 import json import argparse import
我正在将 MSAL 版本 1.x 更新为 MSAL-browser 的 Angular 。所以我正在尝试从版本 1.x 迁移到 2.X.I 能够成功替换代码并且工作正常。但是我遇到了 acquireT
我知道有很多关于此的问题,例如 Getting daily averages with pandas和 How get monthly mean in pandas using groupby但我遇到
This is the query string that I am receiving in URL. Output url: /demo/analysis/test?startDate=Sat+
我正在尝试使用 javascript 中的以下代码访问 Geoserver 层 var gkvrtWmsSource =new ol.source.ImageWMS({ u
API 需要一个包含授权代码的 header 。这就是我到目前为止所拥有的: var fullUrl = 'https://api.ecobee.com/1/thermostat?json=\{"s
如何获取文件中的最后一个字符,如果是某个字符,则删除它而不将整个文件加载到内存中? 这就是我目前所拥有的。 using (var fileStream = new FileStream("file.t
我是这个社区的新手,想出了我的第一个问题。 我正在使用 JSP,我成功地创建了 JSP-Sites,它正在使用jsp:setParameter 和 jsp:getParameter 具有单个字符串。
在回答 StoreStore reordering happens when compiling C++ for x86 @Peter Cordes 写过 For Acquire/Release se
我有一个函数,我们将其命名为 X1,它返回变量 Y。该函数在操作 .on("focusout", X1) 中使用。如何获取变量Y?执行.on后X1的结果? 最佳答案 您可以更改 Y 的范围以使其位于函
我是一名优秀的程序员,十分优秀!