码迷,mamicode.com
首页 > 其他好文 > 详细

给类,实例绑定属性和方法

时间:2018-07-10 11:16:37      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:动态   调用   michael   pytho   ...   object   mic   student   types   

class Student(object):
    pass
>>> s = Student()
>>> s.name = ‘Michael‘ # 动态给实例绑定一个属性
>>> print(s.name)
Michael

>>> def set_age(self, age): # 定义一个函数作为实例方法
...     self.age = age
...
>>> from types import MethodType
>>> s.set_age = MethodType(set_age, s) # 给实例绑定一个方法
>>> s.set_age(25) # 调用实例方法
>>> s.age # 测试结果
25

给类绑定方法:

>>> def set_score(self, score):
...     self.score = score
...
>>> Student.set_score = set_score
>>> s.set_score(100)
>>> s.score
100
>>> s2.set_score(99)
>>> s2.score
99
 

给类,实例绑定属性和方法

标签:动态   调用   michael   pytho   ...   object   mic   student   types   

原文地址:https://www.cnblogs.com/LewisAAA/p/9287059.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!