美文网首页ITS·黑客
【python】给类或实例绑定方法或实例

【python】给类或实例绑定方法或实例

作者: 某米狼 | 来源:发表于2017-05-11 13:57 被阅读8次

    给类或者实例绑定方法或实例:

    >>> class Student(object):
            pass
    
    1. 先定义,然后 类名.新方法=前面定义过的方法
    #给类绑定方法
    >>> def set_score(self, score):
    ...     self.score = score
    ...
    >>> Student.set_score = set_score
    #给实例绑定属性
    >>> s = Student()
    >>> s.name = 'Michael' # 动态给实例绑定一个属性
    >>> print(s.name)
    Michael
    
    1. MethodType()
      s.methodname = MethodType(前面定义过的方法名, s)
    >>> def set_age(self, age): # 定义一个函数作为实例方法
    ...     self.age = age
    ...
    >>> from types import MethodType
    >>> s.set_age = MethodType(set_age, s) # 给实例s绑定一个方法,绑定名称为set_age
    >>> s.set_age(25) # 调用实例方法
    >>> s.age # 测试结果
    25
    
    1. setattr(object,name,value)
      属性name必须先存在
      只能用在实例...吧

    限制实例的属性,比如只允许对Student实例添加name和age属性。
    __slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的

    class Student(object):
        __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
    

    在绑定属性时,检查参数
    Python内置的@property装饰器就是负责把一个方法变成属性调用的

    相关文章

      网友评论

        本文标题:【python】给类或实例绑定方法或实例

        本文链接:https://www.haomeiwen.com/subject/hqrotxtx.html