[英]I'm having an error: "TypeError: 'str' object is not callable" - Python
I'm really confused.我真的很困惑。 I made classes similar to this the one with this one with no errors.
我制作了与此类似的课程,并且没有错误。 So I don't see the problem with this one.
所以我没有看到这个问题。 Please help!
请帮忙!
class champ_info:
def __init__(self, name):
self.name = name
def name(self):
print({self.name}) #I also tried using it with out the {}
v = champ_info('henry')
v.name()
You have an attribute with the same name as a method.您有一个与方法同名的属性。 When you assign
self.name
its object shadows the function object you really wanted.当您分配
self.name
它的对象会self.name
您真正想要的函数对象。
class champ_info:
def __init__(self, name):
self.name = name # <-- this shadows the same-named method
v.name()
translates to (1) get object referenced by "name" (its the string 'henry'
) and (2) call that object. v.name()
转换为(1)获取由“name”引用的对象(它的字符串'henry'
)和(2)调用该对象。 You can't call a string, so boom.你不能叫一个字符串,所以繁荣。
To solve, just come up with a better name for the method, hopefully something that gives a good hint of what it does.要解决这个问题,只需为该方法想一个更好的名称,希望能很好地暗示它的作用。
class champ_info:
def __init__(self, name):
self.name = name
def print_me(self):
print(f"{self.name}")
v = champ_info('henry')
v.print_me()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.