python类内部 "__*__" 方法的作用

#本文是慕课网《Python项目实战-核心技术进阶训练篇》的学习笔记



__new__()

本身是一个类方法,先于__init__()执行,返回一个实例,可以改变实例化行为

class MyClass(tuple):
    def __new__(cls, *args):
        a = [x for x in args]
        return super(MyClass, cls).__new__(cls, a)

    def __init__(self, *args):
        print self  #>> (1, 2,3)
        super(MyClass, self).__init__(*args)


m = MyClass(1, 2, 3)
print m  #>> (1, 2,3)


__dict__

实例属性,用于动态绑定实例属性

class MyClass(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b


m = MyClass(1, 2)
print m.__dict__ #{'a': 1, 'b': 2}

m.c = 3
print m.__dict__  #{'a': 1, 'b': 2, 'c': 3}

m.__dict__["d"] = 4
print m.d  # 4


__slots__

类属型,用于解决动态属性绑定占用内存的问题,需提前声明类属性且不可变更

class MyClass1(object):
    __slots__ = ['a', 'b']

    def __init__(self, a, b):
        self.a = a
        self.b = b

m1 = MyClass1(1, 2)
print m1.a, m1.b #1 2

m1.c = 3 #raise AttributeError


__enter__() and __exit__()

实例方法,用于使实例支持上下文管理(with as).

前者在开始时调用必须返回实例对象self,

后者在结束或者产生错误时调用,__exit__()的参数中exc_type, exc_value, traceback用于描述异常

class MyClass(object):
    def __enter__(self):
        self.f = open('test.txt', 'w')
        return self

    def pname(self):
        print self.f.name

    def for_read(self):
        raise AttributeError("f could only wirte")

    def __exit__(self, exc_type, exc_val, exc_tb):
        print "in exit()"
        self.f.close()


with MyClass() as m:
    m.pname() 
"""
test.txt
in eixt()
"""
with MyClass() as n:
    n.for_read()
"""
in eixt()
AttributeError:f could only write
"""
 




property()

内置工厂函数,用于类内部设置可管理属性

property(fget, fset, fdel)




__lt__()  __le__()  __gt__()  __ge__()  __eq__()  __ne__()

     <                           <=                   >                      >=                             =                     !=

可以实现类之间的大小比较

另有functools.total_ordering可以只定义等于和大于(或小于)就可以比较全部符号

from functools import total_ordering

from functools import total_ordering

@total_ordering
class Rect(object):
    def __init__(self, length, width):
        self.lenght = length
        self.width = width

    def area(self):
        return self.lenght * self.width

    def __lt__(self, obj):
        return self.area() < obj.area()

    def __eq__(self, obj):
        return self.area() == obj.area()


r1 = Rect(1, 2)
r2 = Rect(1, 4)

print r1 > r2 #False

__del__()

实例方法,用于在python垃圾回收机制回收变量时执行

class MyClass(object):
    def __del__(self):
        print 'in __del__'

c = MyClass()
c = 4 #in __del__



你可能感兴趣的:(类,python,实例)