python下的一些特殊属性(几个实例说明)

实例1:

#-*-coding:UTF-8-*-

class  FirstDemo(object):
    """
        这里是一个doc
    """
    a=10   #类属性
    def  demo(self):
        """
        第一个方法
        """
        pass
    def demo2(self):
        """
        第二个方法
        """
        pass
print FirstDemo.__dict__   #打印出FirstDemo类的所有属性和方法,结果为一个字典
print FirstDemo.__bases__  #类的基类
print FirstDemo.__doc__    #类的docstring
print FirstDemo.__name__   #类的名字
print FirstDemo.__module__ #类所在模块,如果是主文件,就是__main__


print FirstDemo().__class__    #类的类型<class '__main__.FirstDemo'>
print FirstDemo().__module__   #实例类型所在模块
print FirstDemo().__dict__     #对象的字典,存储所有实例成员信息


 实例2:

#-*-coding:UTF-8-*-

class  FirstDemo(object):
    b=100   #类属性
    def __init__(self):
        FirstDemo.b=200
    def __repr__(self):
        return "repr方法"
    def __str__(self):
        return "str方法"
    def  demo(self):
        print FirstDemo.b
a=FirstDemo()
print a.__repr__()
print a.__str__()
print "--------"
a.demo()


结果:

repr方法
str方法
--------
200

序号 目的 所编写代码 Python 实际调用
初始化一个实例 x = MyClass() x.__init__()
字符串的“官方”表现形式 repr(x) x.__repr__()
字符串的“非正式”值 str(x) x.__str__()
   
   

最后打印的b的值为200,是因为__init__()方法的调用发生在实例被创建之后。

实例3(对象属性的操作):

#-*-coding:UTF-8-*-

class  FirstDemo(object):
    b=100   #类属性
    def __init__(self):
        FirstDemo.b=200
    def __repr__(self):
        return "repr方法"
    def __str__(self):
        return "str方法"
    def  demo(self):
        print FirstDemo.b
a=FirstDemo()
a.temp=500   #为对象添加一个属性
print a.__dict__  #查看对象的实例属性字典
print dir(a)   #列出实例的属性和方法集合
del a.temp	#删除对象中的temp属性
print a.__dict__
print dir(a)


 

原文地址:https://www.cnblogs.com/chenjianhong/p/4145145.html