【问题标题】:AttributeError: 'str' object has no attribute '__dict__'AttributeError:“str”对象没有属性“__dict__”
【发布时间】:2019-12-02 03:32:51
【问题描述】:

我想在类中查找实例变量,但出现错误 请任何人都可以帮助我在哪里出错 提前致谢

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"))

【问题讨论】:

  • 如果您的问题已解决,请将答案标记为正确,这样您的问题就可以结束了。

标签: python python-3.x switch-statement instance-variables


【解决方案1】:

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

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)

【讨论】:

    猜你喜欢
    • 2011-11-21
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 2021-10-04
    • 2021-09-25
    • 2014-03-04
    相关资源
    最近更新 更多