尝试在python中使用装饰器时出现属性错误

时间:2020-08-11 03:52:13

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

我在下面的代码中出现属性错误 这是结果

回溯(最近通话最近): 在第18行的文件“ C:/Users/fortu/PycharmProjects/telusko.py/inheritance.py” 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()

1 个答案:

答案 0 :(得分:0)

您的get_church方法返回一个string的{​​{1}},它被分配给RCCG。这就是为什么在调用p1时得到AttributeError的原因。

p1.name()

im试图在一行中打印fname lname和教堂名称RCCG

您必须对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 方法进行更改以包含name

self.church

然后从def name(self): print(f'{self.fname}, {self.lname}, member of {self.church}') 调用name方法。

p