打印类属性

huangapple go评论65阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年5月6日 16:26:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76187894.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定