-2

I started with Python's classes and I want to do something like that:

class First:
    def __init__(self):
        self.value = 1

    @classmethod
    def func(cls):
        print(self.value)


second = First()
second.func()

But i can't access self.value of the class. Can anybody help me?

MaxPowers
  • 5,235
  • 2
  • 44
  • 69
  • 2
    when using `classmethod`, you want to pass `cls` not `self`. But class methods cannot and should not depend on the state of the instance. https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner – Buckeye14Guy Feb 17 '20 at 17:22
  • 1
    `@classmethod`s take `cls`, which is the class. Remove the decorator if you want to take `self` which is the object instance. – ruohola Feb 17 '20 at 17:26

3 Answers3

0

If you just want to create a function in your class and use self parameters just do that :

class First:
    def __init__(self):
        self.value = 1

    def func(self):
        print(self.value)


second = First()
second.func()
Ranga
  • 1
  • 2
0

IIUC then your class should look like the following:

class First:
    value = 1

    @classmethod
    def func(cls):
        print(cls.value)
gold_cy
  • 13,648
  • 3
  • 23
  • 45
0

Is @classmothod necessary?
If it is eliminated, the class works well.

class First:
    def __init__(self):
        self.value = 1

    def func(self):
        print(self.value)

second = First()
second.func()
Kimpro
  • 81
  • 2
  • 11