Discuss / Python / 求大神帮我看看

求大神帮我看看

Topic source

这是我的代码slot.py:

class Student(object):
    __slots__=('name','age')#定义属性插槽,只能插入指定的这些属性

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

from types import MethodType
#给实例临时增加方法
s1=Student()

s1.set_age=MethodType(set_age,s1)
s1.set_age(20)
print(s1.age)在此插入代码

这是运行情况,到底哪里错了!?

D:\1学习笔记\05Python\0615>slot.py
Traceback (most recent call last):
  File "D:\1学习笔记\05Python\0615\slot.py", line 24, in <module>
    s1.set_age=MethodType(set_age,s1)
AttributeError: 'Student' object has no attribute 'set_age'在此插入代码

你仔细看看报错的原因AttributeError

上面已经说明了 使用了slots 该类的实例 会实例限制添加属性

你的Student 类只能添加 age 和name的属性

廖雪峰

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

缩进,缩进,缩进

Nicktimebreak

#4 Created at ... [Delete] [Delete and Lock User]
 __slots__=('name','age')后面加上'set_age'

本来student父类已经有set_age的方法了,不需要再给他的实例s1重新定义一遍,直接用s1.set_age就可以

你这个set_age()是定义在class外部的,不是class的方法,但s1又继承于class,所以会报错。

我认为应该是这样:

class Student(object):
    __slots__=('name','age')

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

_周思思_

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

由于'score'没有被放到slots中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误。

使用slots要注意,slots定义的属性仅对当前类实例起作用

修改代码: 第一种:

 __slots__=('name','age')改为__slots__=('name','age', 'set_age')

第二种:

编写一个类,继承Student,s1实例化Student的子类。

slots=('name','age')改为slots=('name','age', 'set_age')

你这应该有两种改进方法:

一、尝试一下用类属性绑定方法,不要用实例属性 例:类.set_score=MethodType(set_score,类),用这种情况,可以不用理会slots对变量的限制,因为在set_score方法中可以添加属性变量。

二、尝试实例属性绑定方法,如你的这种,必须在slots中添加set_score这个方法进去,后续才可以该方法对age进行赋值调用。


  • 1

Reply