英文:
Printing class attribute
问题
Printing a class attribute from a function defined within the same class.
class person:
name = "xyz"
def show(self):
print(self.name)
a = person
a.show()
Output:
TypeError: person.show() missing 1 required positional argument: 'self'
Why the above code is throwing error while the code below is working fine?
class person:
def __init__(self, name):
self.name = name
def show(self):
print(self.name)
a = person("xyz")
a.show()
Output: xyz
英文:
Printing a class attribute from a function defined within the same class.
class person:
name = "xyz"
def show(self):
print(self.name)
a = person
a.show()
Output:
TypeError: person.show() missing 1 required positional argument: 'self'
Why the above code is throwing error while the code below is working fine?
class person:
def __init__(self, name):
self.name = name
def show(self):
print(self.name)
a = person("xyz")
a.show()
Output: xyz
答案1
得分: 1
在第一种情况下,您试图访问尚未设置的内容,即类的特定实例的名称。
要定义这是一个类方法,您需要使用相应的装饰器。
@classmethod
def show(cls):
print(cls.name)
顺便说一下,您可以将cls命名为您喜欢的任何名称,但通常在类属性上使用cls,在实例属性/方法上使用self。
如果您不需要这种方式访问属性,还有其他方法:
a.name
person.name
英文:
In the first case you are trying to access something that has not been set, which is the name of the particular instance of the class.
Το define that this is a class method you need to use the respective decorator.
@classmethod
def show(cls):
print(cls.name)
You can name cls as you like btw, but it is common to use cls for class attributes and self for instance attributes/methods
If you do not need to this other ways to access the attribute would be
a.name
person.name
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论