Search code examples
pythonclassmethodsattributesself

Python 3 self. attributes in method


Suppose there is a simple class with attributes and method.

class c:

    def __init__(self, a, b):
        self.a = a
        self.b = b

    def f(self):
        return(self.a + self.b)

plus = c(2, 2)
print(c.f(plus))

print(c(2, 2).f())

If I print this, creating an object first, it all works. But when I pass the attributes to the method itself, I get an error.

print(c.f(2, 2))

So, is it possible to pass attributes to the method itself without creating an object, as in a normal function? Am I doing something wrong, or should I use normal function instead of method in this case? Thank you guys and girls for helping ;)


Solution

  • You can use a staticmethod:

    class c:
      def __init__(self, a, b):
        self.a = a
        self.b = b
      @staticmethod
      def f(*args):
        return sum(args)
    
    
    print(c.f(2, 2))
    

    Output:

    4