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
因为你没有调用s.set_age。。。