现在的位置: 首页 > 综合 > 正文

Python强大的内置方法

2017年11月27日 ⁄ 综合 ⁄ 共 2850字 ⁄ 字号 评论关闭

写在前面

相信每种编程语言都会有很多的内置方法,就像内置数据类型一样。但python的这些内置方法是很特殊的,今天就列举几个跟“对象”相关的内置方法。

为了方便举例说明,先作如下的准备:

  1. 定义一个空类

    >>> class A():
        def __init__(self,name):
            self.name = 'name

  2. 创建该空类的实例

    >>> a = A('An')

开始

数据准备完毕,下面开始我们的探索之旅

查看某对象有哪些属性/方法

在python中你可能经常会看到这么一句话,“一切皆对象”,我们将要使用的对象也就是这句话中的对象。我们使用python内置dir([object]) -> list of strings方法来看看前面定义的A类实例a有哪些方法:

>>> dir(a)
['__doc__', '__init__', '__module__', 'name']
>>> 

dir([object]) -> list of strings可以带一个object参数,也可以不带参数

  1. 如果带参数将返回该参数对象包含的全部方法、属性名称的字符串列表,子类实例将包含父类的全部属性
  2. 如果不带参数将当前所在代码块作为object

是否真的有某个属性/方法

在其他大多数语言当中可能不会用到这样的方法,hasattr(object, name) -> bool判断object是否有叫name的属性或者方法,有返回True,没有返回False。object为对象,name为字符串。如下判断a实例是否有"name"属性:

>>> hasattr(a,'name')
True
>>> 
>>> hasattr(a,'age')
False
>>> 

通常,判断都不是最终目的,判断总是会有后续的操作的。我们在判断某对象是否包含某属性之后,我们怎么获取该属性的引用呢?

获取某对象指定名称属性

使用getattr(object, name[, default]) -> value来获取某对象特定名称的属性/方法,参数意义同hasattr(object, name) -> bool,default为可选参数,详细说明参见下表(假定使用a作为参数object):

object name default 返回
a name 'James' 'An'
a age 'James' 'James'
a name 未指定 'An'
a age 未指定 raise AttributeError

从上表我们可以看出,default只有在object没有name属性时才有意义,如果default没有指定,且object没有name属性将抛出异常

设置某对象指定名称属性的值

我们在获取对象的某个值后,可能需要重新设置该属性的值,这时候我们需要使用setattr(object, name, value),value为该属性的新值,备注:如果object没有name属性,将会添加该属性并设置值为value,如下:

>>> getattr(a,'name')
'An'
>>> setattr(a,'name','James')
>>> getattr(a,'name')
'James'
>>> 

当没有该属性时,如下:

>>> dir(a)
['__doc__', '__init__', '__module__', 'name']
>>> setattr(a,'age',26)
>>> dir(a)
['__doc__', '__init__', '__module__', 'age', 'name']
>>> getattr(a,'name')
'James'
>>> 

谁是属性,谁是方法?

我们可以使用getattr(object, name[, default]) -> value来获取object的name属性/方法,在某些场合,我们需要明确的知道其返回的值是属性?还是方法?方法可以调用,但属性不能。callable(object) -> bool方法可以轻松辨别,如下:

>>> callable(a.name)
False
>>> callable(a.__init__)
True
>>> 

callable(object) -> bool可以与getattr(object, name[, default]) -> value结合使用

如果是方法,该如何调用?

如果使用callable(object) -> bool判断出getattr(object, name[, default]) -> value获取的是方法,调用方式如下:

>>> class A():
	def __init__(self,name):
		self.name = name
	def showName(self):
		print self.name

		
>>> a = A('An')
>>> func = getattr(a,'showName')
>>> if callable(func):
	print 'func is callable'
	func()
	# getattr(a,'showName')() is OK

func is callable
An
>>> 

最后

使用python内置方法help,你将会知道很多。使用方法如下:

>>> help(dir)
Help on built-in function dir in module __builtin__:

dir(...)
    dir([object]) -> list of strings
    
    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.

>>> help(a)
Help on instance of A in module __main__:

class A
 |  Methods defined here:
 |  
 |  __init__(self, name)
 |  
 |  showName(self)

>>> 
>>> help(A)
Help on class A in module __main__:

class A
 |  Methods defined here:
 |  
 |  __init__(self, name)
 |  
 |  showName(self)

>>> 

什么不懂,就放到help后面的括号中去吧

【上篇】
【下篇】

抱歉!评论已关闭.