python类学习笔记

来源:互联网 发布:mpu9250 九轴融合算法 编辑:程序博客网 时间:2024/05/01 14:50

构造函数

    def __init__(self)

内部变量访问权限

    __var 不允许访问    __var__ 允许访问    _var 尽量不要访问

动态绑定方法

    假如        class Stu(object):            pass    为实例绑定方法        from types import MethodType        s = Stu()        s.set_age = MethodType(set_age, s, Stu)        s.set_age()    为类绑定方法        from types import MethodType        Stu.set_age = MethodType(set_age, None, Stu)        s = Stu()        s.set_age()

限制绑定的属性

    __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称    仅对当前类起作用,对继承的子类是不起作用的    除非在子类中也定义__slots__.这样,子类允许定义的属性就是自身的__slots__加上父类的__slots__

@property

    使用property装饰器,可以用访问对象属性的方式访问对象方法    同时,property装饰器还会生成一个xxx.setter装饰器    class Stu(object):        __name = ''        __age = 0        @property        def name(self):            return self.__name        @property        def age(self):            return self.__age        @age.setter        def age(self, value):            if not isinstance(value, int):                raise ValueError('it is not type of int')            if value > 150 or value < 0:                raise ValueError('must between 0 and 150')            self.__age = value

特殊变量和方法

    __len__()方法是为了能让该class作用于len()函数    __str__()方法是打印实例时输出的内容    __repr__()方法是直接显示实例时输出的内容.但是通常__str__()和__repr__()代码都是一样的,所以使用__repr__ = __str__    __iter__()方法让该class可以用于for..in..循环    __getitem__()方法是把对象视作list或dict来对集合访问    __setitem__()方法是把对象视作list或dict来对集合赋值    __getattr__()方法是在用户访问不存在的变量时,会调用该方法    __call__()方法是可以使该实例直接被调用
0 0
原创粉丝点击