【问题标题】:Python - AttributeError: type object 'MyClass' has no attribute 'name'Python - AttributeError:类型对象'MyClass'没有属性'name'
【发布时间】:2015-04-08 11:36:05
【问题描述】:

我有 3 个 python 文件。

MyModule.py

class MyClass:
    def __init__(self, name):
        self.name = name

    @classmethod
    def hello(self):
        print('Hello ' + self.name)

Loader.py

import pickle
from MyModule import *

me = pickle.load(file('my_pkl.pickle','rb'))
me.hello()

Dumper.py

import pickle
from MyModule import *

me = MyClass('Anil')
pickle.dump(me, open('my_pkl.pickle','wb'))

当我执行 Loader.py 时出现以下错误:

AttributeError: type object 'MyClass' has no attribute 'name'

如何访问名称实例变量?

【问题讨论】:

  • 为什么是me.hello()
  • @thinkerou 我只想在me 实例上调用hello() 方法
  • 但是,me 和类 MyClass 无关紧要。
  • 请阅读hereherehere 关于@staticmethod@classmethod

标签: python


【解决方案1】:

您正在使用实例方法作为类方法。使其成为实例方法。

# remove @classmethod decorator
# called on instance: me.hello()

def hello(self):
    print('Hello ' + self.name) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-22
    • 2017-04-15
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多