python MethodType方法詳解和使用


python 中MethodType方法詳解和使用

廢話不多說,直接上代碼

#!/usr/bin/python
# -*-coding:utf-8-*-

from types import MethodType 
"""
文件名 class2.py
MethodType 測試
"""
# 首先看第一種方式
#創建一個方法
def set_age(self, arg):
    self.age = arg    
#創建一個類    
class Student(object):
    pass

#------以上為公共部分

s_one = Student() #給student 創建一個方法 但這里不是在class中創建而是創建了一個鏈接把外部的set_age 方法用鏈接知道Student內 s_one.set_age = MethodType(set_age,s_one,Student) s_one.set_age(32) #調用實例方法 print s_one.age #》》》》結果 32 s_two = Student() s_two.set_age(100) #這里來驗證下是在類內有方法還是類外有方法。 print s_two.age #》》》》結果Traceback (most recent call last): #》》》》 File "class2.py", line 22, in <module> #》》》》 s_two.set_age(100) #這里來驗證下是在類內有方法還是類外有方法。 #》》》》 AttributeError: 'Student' object has no attribute 'set_age'

看另一種

#直接用類來創建一個方法  不過此時還是用鏈接的方式在類外的內存中創建
Student.set_age = MethodType(set_age,Student)
#此時在創建實例的時候外部方法 set_age 也會復制 這些實例和Student類都指向同一個set_age方法
new1 = Student()
new2 = Student()
new1.set_age(99)
new2.set_age(98)   #第二個會覆蓋第一個 
print (new1.age,new2.age)   #看結果 2個都是98  
#》》》》(98, 98)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM