Stack Overflow
Stack Overflow

Reputation: 457

Access class attributes in python from class method

Assuming I have the following class:

class Foo:
 bar : str
 @classmethod
 def foobar(self): #self = cls
  print(??)

And I want to print the attribute bar in foobar. How do I do that? self.bar gives me the error:

AttributeError: type object 'Foo' has no attribute 'bar'

How do I do that?

Upvotes: 2

Views: 4874

Answers (2)

dubber
dubber

Reputation: 21

Because the str isn't assigned an actual value.

You should also indent with 4 spaces, not 1.

Upvotes: 0

Danish Bansal
Danish Bansal

Reputation: 700

Following is the way

class Foo:
    bar: str = None  # Initialize your attribute in this way

    @classmethod
    def foobar(cls):  # self = cls
        print(cls.bar) 


a = Foo()
a.foobar()

Upvotes: 3

Related Questions