Valeo
Valeo

Reputation: 3

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 ;)

Upvotes: 0

Views: 897

Answers (3)

James Knott
James Knott

Reputation: 1578

Think of classes as the mold. You don't actually interact with the mold itself, but you use the mold to create objects, that you then can interact with. In order to do something with the object, you have to create it first. This is called Instantiation.

Upvotes: 1

user3483203
user3483203

Reputation: 51185

If you want to avoid creating an instance of your class, you can use the @staticmethod decorator:

class C:

    @staticmethod
    def f(a, b):
        return a + b

>>> C.f(2, 2)
4

I would also recommend following PEP 8 Conventions and using CapWords for naming classes.

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71471

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

Upvotes: 1

Related Questions