1. 程式人生 > >類的特殊成員方法

類的特殊成員方法

表示 打印 操作 查看 dict func elf mod 代碼

類的成員除了有類變量、實例變量、方法外,還有一些特殊的成員方法,下面列舉些比較重要的特殊成員:

類的特殊成員方法

1、__doc__: 表示類的描述信息,

  大家都知道,在開發中應該在代碼中多加註釋,來增強代碼的可讀性。用__doc__就可以查看函數或類的描述信息。

def  test():
    ‘‘‘
    this is  a  test function
    ‘‘‘
    pass
class ClassTest(object):
    ‘‘‘
    this is a class  method
    ‘‘‘
print test.__doc__
print ClassTest.__doc__

2、__module__和__class__

  __module__ 表示對象所在的模塊

  __class__ 表示對象所在的類是什麽

3、__dict__: 查看類或對象中的所有成員

  如果是類直接調這個方法表示打印類中的類變量、類方法、類的特殊方法等,但不可打印實例變量。

  如果是對象調用這個方法的話,表示打印對象的實例變量,但不可打印類中的類變量、類方法、類的特殊方法等。

  這個方法很重要,一定要多掌握,用此方法打印的結果為字典。

  

class ClassTest(object):
    ‘‘‘
    this is a class  method
    ‘‘‘
    commity_data = 123
    def  __init__(self,name,age):
        self.name = name
        self.age = age
    def  hello(self):
        pass
    def  hi(self):
        pass

user_info = ClassTest(‘goser‘,23)
print ClassTest.__dict__
print user_info.__dict__

輸出結果為:

{‘__module__‘: ‘__main__‘, ‘hi‘: <function hi at 0x00BE5430>, ‘__dict__‘: <attribute ‘__dict__‘ of ‘ClassTest‘ objects>, ‘hello‘: <function hello at 0x00BE54B0>, ‘__weakref__‘: <attribute ‘__weakref__‘ of ‘ClassTest‘ objects>, ‘__doc__‘: ‘\n this is a class method\n ‘, ‘__init__‘: <function __init__ at 0x00BE5470>, ‘commity_data‘: 123}


{‘age‘: 23, ‘name‘: ‘goser‘}

4、__call__: 如果類中定義了此方法的話,那麽在生成類對象後,就可以在類對象加上()就可以直接調用__call__()方法

  

class ClassTest(object):
    ‘‘‘
    this is a class  method
    ‘‘‘
    commity_data = 123
    def  __init__(self,name,age):
        self.name = name
        self.age = age
    def  hello(self):
        pass
    def  hi(self):
        pass
    def  __call__(self, *args, **kwargs):
        print ‘you input pattern is %s|%s:‘ %(args,kwargs)

user_info = ClassTest(‘goser‘,23)
user_info(1,2,3,sex=‘male‘)

輸出結果為:
you input pattern is (1, 2, 3)|{‘sex‘: ‘male‘}:

5、__str__:如果類中定義了此方法,那麽在打印對象的時候默認打印的是此方法的返回值

  

class ClassTest(object):
    ‘‘‘
    this is a class  method
    ‘‘‘
    commity_data = 123
    def  __init__(self,name,age):
        self.name = name
        self.age = age
    def  hello(self):
        pass
    def  hi(self):
        pass
    def  __call__(self, *args, **kwargs):
        print ‘you input pattern is %s|%s:‘ %(args,kwargs)
    def  __str__(self):

        return ‘the class commity pattern is %s:‘ % self.commity_data

user_info = ClassTest(‘goser‘,23)
user_info(1,2,3,sex=‘male‘)
print user_info

運行結果為:
you input pattern is (1, 2, 3)|{‘sex‘: ‘male‘}:
the class commity pattern is 123:

6、__getitem__、__setitem__、 __delitem__

  表示用以引用索引操作,比如字典,以上分別表示獲取、設置、刪除數據

類的特殊成員方法