Python类对象的特殊方法
查看类包含的方法
# coding=utf-8
from pprint import pprint as pp
class A(object):
pass
pp(dir(A))
下面是打印内容,也就是后面探讨的内容,下面让我们一起来看看Python类对象的内建方法都有哪些作用:
['__class__',
'__delattr__',
'__dict__',
'__doc__',
'__format__',
'__getattribute__',
'__hash__',
'__init__',
'__module__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__']
1.__class__方法
一句话总结:__class__方法等同于Python的内建方法type
# coding=utf-8
from pprint import pprint as pp
class A(object):
pass
print A.__class__, type
打印结果:
<type 'type'> <type 'type'>
这意味着A.__class__和Python的内建方法type是同一个内建方法,所以让我们看看type的这个注释:
def __init__(cls, what, bases=None, dict=None): # known special case of type.__init__
"""
type(object) -> the object's type
type(name, bases, dict) -> a new type
# (copied from class doc)
"""
pass
- type(object) ,返回A的类型,这种用法大家都经常使用;
- type(name, bases, dict),生成新的类型,用于代码中动态生成新的类型,参数name用于指定新生成的类名,参数bases,用于指定继承父类的元组,dict可以动态的为新生成的类指定属性,下面来个例子,用于证明__class__方法与type等效:
# coding=utf-8
from pprint import pprint as pp
class A(object):
def __init__(self):
self.PropertyA = 1
class B(object):
def __init__(self):
self.PropertyB = 2
def B_method(self)