Python2.7类的绑定

本文介绍Python2.7中如何使用MethodType函数将外部函数绑定到对象或类上,探讨不同绑定方式下对象间的影响,并展示了如何使用__slots__来限制类的属性绑定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python2.7类的绑定

利用 MethodType()函数来绑定

绑定到对象

对于语句:stu1.SetName = types.MethodType(SetName, stu1, Student)来说
MethodType是把外部函数SetName()绑定到对象stu1的身上成为它的一个方法
绑定只可以通过本对象来可以调用这个方法

绑定到类

语句Student.SetAge = types.MethodType(SetAge, None, Student)Student.SetScore = types.MethodType(SetScore, Student)
不同点不同对象调用的外部函数处于不同的空间,所以不同对象之间互不影响这种情况下,不同对象调用的外部函数处于同一空间,所以后面对象调用外部函数会影响前面的结果,即对象之间是相互影响的
相同点MethodType是把外部函数SetName()绑定到Student类的身上成为它的一个方法绑定一次就可以所有的对象都可以调用这个方法

样例代码

# -*- 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()
#这种情况下,不同对象调用的外部函数处于同一空间,所以后面对象调用外部函数会影响前面的结果,即对象之间是相互影响的

使用__slots__来限制绑定

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

stu1=Student()
stu1.name="Tom"
print stu1.name
stu1.age=18
print stu1.age
stu1.score=90
print stu1.score

输出

Tom
18
AttributeError: 'Student' object has no attribute 'score'

综上所述:
使用__slots__是用tuple定义允许绑定的属性名称

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Gowi_fly

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值