python3.7 slots 无法将函数绑定到类的实例上?

python小白,按廖雪峰的教程学到类的slots时候,无法将类外定义的函数绑定到类的实例
代码:

# -*- coding: utf-8 -*-

class Student(object):
    pass

s = Student()
# s.name = 'Material'
# print(s.name)

def set_age(self, age):
    self.age = age

from  types import MethodType
s.set_age = MethodType(set_age, s)
print(s.age)

报错如下:


$ python slots.py
Traceback (most recent call last):
File "slots.py", line 21, in <module>
print(s.age)
AttributeError: 'Student' object has no attribute 'age'

请问是啥原因呢?3Q
alphanow_LA
最佳答案

因为你没有调用s.set_age。。。

5年前 评论
讨论数量: 2
alphanow_LA

因为你没有调用s.set_age。。。

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!