Discuss / Python / 设定限制属性后,实例不能动态添加方法的问题

设定限制属性后,实例不能动态添加方法的问题

Topic source

我有疫苗

#1 Created at ... [Delete] [Delete and Lock User]

#类的定义 class Teacher(object): slots = ('name','age')

#函数的定义 def printStr(self): print("好好学习") t = Teacher() t.printStr = MethodType(printStr, t)

#为什么报这个错误,不明白求解答 AttributeError: 'Teacher' object has no attribute 'printStr'

邱小子vip

#2 Created at ... [Delete] [Delete and Lock User]

slot未限制方法

我也遇到这个问题了

slots=('name','age','printStr')

我觉得你没加这一句吧: from types import MethodType

我认为是,因为已经限制了t(实例)的属性,所以在执行 t.printStr = MetthodType(printStr,t) 语句中,等号左边就编译通不过了,你换成Teacher类里面指定的属性,比如t.name = MetthodType(printStr,t),就能通过了

我想了想,觉得应该是 t.printStr = MethodType(printStr, t) 等号右边是绑定方法,等号左边是赋值的变量,也就是把绑定的方法赋值给了变量t.printStr 左边的变量可以是其他数值(你设置的变量为printStr),比如可以写成 k = MethodType(printStr, t) 这是给class添加的方法,实例化的时候,不管创建几个实例,t1,t2,t3 这些实例都用class动态添加的方法k, 打印print (k()) 都会输出绑定的class方法‘好好学习’。 后面打印print (t.printStr)的时候,输出的是t的属性attrbute “printStr”. 但是这个属性并没有被创建。所以会报错

上面回复更正下,class方法应该是k = MethodType(printStr, Teacher)#(方法,类) # 实例绑定对应为(方法/属性,实例)

a刘宇

#9 Created at ... [Delete] [Delete and Lock User]

t.printster = MethodType(printstr, t)这里有问题吧, t是类Teacher的一个实例,而类Teacher中并未定义printstr这个函数,所以不可以通过实例t调用函数printstr。 可以改为:t1 = MethodType(printstr, t) print(t1())

限制属性后,实例可以动态添加方法,就是这个方法中涉及的属性只能是限制的那几个属性,如果有其他属性调用时也会出错。动态绑定的方法也不能用s.set_score=MethodType(set_score,s1),因为python会将set_score认为是一个属性,而不是方法。可以直接用a=MethodType(set_score,s1)。但因为score本身不在限制的两个属性内,所以调用时也会报错。

class Student(object): slots=('name','age')# 用tuple定义允许绑定的属性名称 s1=Student() 绑定属性name和age s1.name='lily' s1.age=18 print(s1.name,'\n',s1.age)

#s1.score=99 ##AttributeError: 'Student' object has no attribute 'score' 由于'score'没有被放到slots中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误。 用以上上述两种方法对实例绑定方法

def set_score(self,score):##定义set_score方法 self.score=score 方法一 s1.set_score=set_score%AttributeError: 'Student' object has no attribute 'set_score' s1.set_score(s1,98)%调用s1的set_score方法 方法二 from types import MethodType

#s1.set_score= MethodType(set_score,s1)#AttributeError: 'Student' object has no attribute 'set_score' 方法三:直接将函数赋值给a,然后再调用 a=MethodType(set_score,s1) a(99)#AttributeError: 'Student' object has no attribute 'score' 上述两种方法均不可以,因为python会将set_score看成属性而不是方法,直接用a=MethodType(set_score,s1)就可以了。 但是底下调用时还是会出错。因为这个类中是没有score属性的。 因此重新写了个reset_age的函数,因为这个类中有age这个属性,所以调用不会出错

def reset_age(self,age):##定义set_score方法 self.age=age from types import MethodType a=MethodType(reset_age,s1) a(21) print(type(a)) print(s1.age)


  • 1

Reply