Python中MethodType()函数的用法

  • Python 程序
# -*- coding: utf-8 -*-
import types
#定义类
class Student:
    def __init__(self):
        pass
    def PrintName(self):
        print('name = ', self.name)
    def PrintAge(self):
        print('age = ', self.age)
    def PrintScore(self):
        print('score = ', self.score)
#外部函数
def SetName(self, name1):
    self.name = name1
def SetAge(self, age1):
    self.age = age1
def SetScore(self, score1):
    self.score = score1

stu1 = Student()
stu2 = Student()
stu3 = Student()
#1. 将外部方法绑定到对象实例上
stu1.SetName = types.MethodType(SetName, stu1, Student)
stu2.SetName = types.MethodType(SetName, stu2, Student)
stu3.SetName = types.MethodType(SetName, stu3, Student)

stu1.SetName('hello')
stu2.SetName('world')
stu3.SetName('python')

stu1.PrintName()
stu2.PrintName()
stu3.PrintName()
#此时只能通过特定的对象调用绑定的外部函数

#2. 将外部方法绑定到类上(有None参数)
Student.SetAge = types.MethodType(SetAge, None, Student)
stu4 = Student()
stu5 = Student()
stu6 = Student()

stu4.SetAge(10)
stu5.SetAge(20)
stu6.SetAge(30)

stu4.PrintAge()
stu5.PrintAge()
stu6.PrintAge()
#这种情况下,不同对象调用的外部函数处于不同的空间,所以不同对象之间互不影响

#3. 将外部方法绑定到类上(没有None参数)
Student.SetScore = types.MethodType(SetScore, Student)
stu7 = Student()
stu8 = Student()
stu9 = Student()

stu7.SetScore(70.5)
stu8.SetScore(80.5)
stu9.SetScore(90.5)

stu7.PrintScore()
stu8.PrintScore()
stu9.PrintScore()
#这种情况下,不同对象调用的外部函数处于同一空间,所以后面对象调用外部函数会影响前面的结果,即对象之间是相互影响的

  • 执行结果
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值