AttributeError: 'str' object has no attribute '__dict__'
AttributeError: 'str' object has no attribute '__dict__'
我想在 class 中查找实例变量,但出现错误
请任何人都可以帮助我我要去错的地方
提前致谢
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"))
class 的名称不应该是字符串您的代码使用真正的 class 对象,因此更改为:
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)
我想在 class 中查找实例变量,但出现错误 请任何人都可以帮助我我要去错的地方 提前致谢
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"))
class 的名称不应该是字符串您的代码使用真正的 class 对象,因此更改为:
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)