0

我想在课堂上找到实例变量,但我收到错误请任何人帮助我在哪里出错提前谢谢

class PythonSwitch:

    def switch(self, typeOfInfo,nameofclass):
        default = "invalid input"
        return getattr(self, 'info_' + str(typeOfInfo), lambda: default)(nameofclass)

    def info_1(self,nameofclass):
        print("Class name : ",__class__.__name__)
        print("---------- Method of class ----------")
        print(dir(nameofclass))
        print("---------- Instance variable in class ----------")
        print(nameofclass.__dict__)

    def info_2(self,nameofclass):
        print("---------- Method of class ----------")
        print(dir(nameofclass))

    def info_3(self,nameofclass):
        print("---------- Instance variable in class ----------")
        print(nameofclass.__dict__)


s = PythonSwitch()

print(s.switch(1,"PythonSwitch"))
print(s.switch(0,"PythonSwitch"))
4

1 回答 1

2

类的名称不应是您的代码使用真实类对象的字符串,因此请更改为:

s = PythonSwitch()

print(s.switch(1,PythonSwitch))
print(s.switch(0,PythonSwitch))

以您所做的方式进行操作,只是传递了一个字符串对象,如您的输出所述,该对象不构成__dict__属性。

编辑 您的代码中还有一个错误:

return getattr(self, 'info_' + str(typeOfInfo), lambda: default)(nameofclass)

这一行是不正确的,因为您的 lambda 表达式不期望任何值,它应该是因为每个方法都至少获取一个参数,即self. 因此,您需要将其更改为:

return getattr(self, 'info_' + str(typeOfInfo), lambda self: default (nameofclass)

于 2019-07-24T04:13:35.750 回答