我想在类中查找实例变量,但遇到错误 有谁能帮我解决问题吗 提前谢谢
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"))
类的名称不应是字符串您的代码使用真实的类对象,因此更改为:
这样做只是传递一个string对象,正如输出所述,它不会构成一个
__dict__
属性。在编辑 代码中还有一个错误:
return getattr(self, 'info_' + str(typeOfInfo), lambda: default)(nameofclass)
这行是不正确的,因为lambda表达式不需要任何值,而且应该是因为每个方法都至少得到一个参数
self
。所以您需要将其更改为:return getattr(self, 'info_' + str(typeOfInfo), lambda self: default (nameofclass)
相关问题 更多 >
编程相关推荐