【问题标题】:I got an attribute error while trying to use a decorator in python尝试在 python 中使用装饰器时出现属性错误
【发布时间】:2020-11-30 17:02:37
【问题描述】:

我在下面的代码中遇到了属性错误 这是结果

Traceback(最近一次调用最后一次): 文件“C:/Users/fortu/PycharmProjects/telusko.py/inheritance.py”,第 18 行,在 p1.name() AttributeError: 'str' 对象没有属性 'name'

class Church:

    church = 'RCCG'

    def __init__(self, fname, lname):
        self.fname = fname
        self.lname = lname

    @classmethod
    def get_church(cls):
        return cls.church

    def name(self):
        print(f'{self.fname}, {self.lname}, member of ')

p = Church('John','Doe')
p1 = p.get_church()
p1.name()

【问题讨论】:

  • 您的get_church 返回一个字符串。你想达到什么目的?
  • 我试图在一行中打印 fname lname 加上 RCCG 的教堂名称

标签: python python-3.x class subclass python-decorators


【解决方案1】:

您的get_church 方法返回一个string,即分配给p1RCCG。这就是为什么当您调用 p1.name() 时会得到 AttributeError

p1 = p.get_church() # p1 value is RCCG

# above is equivalent to
p1 = p.church

# now when you do this `p1.name()` it's equivalent to doing
"RCCG".name() # this is where you'll get an error

我试图在一行中打印 fname lname 加上教堂名称,即 RCCG

您必须更改您的 name 方法以包含 self.church

def name(self):
    print(f'{self.fname}, {self.lname}, member of {self.church}')

然后从p调用name方法。

p = Church('John','Doe')
p.name()

【讨论】:

    猜你喜欢
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 2023-03-07
    相关资源
    最近更新 更多