1

I read that the first parameter of methods is the instance the method is called on. I dont understand why when i write this

class A:
    def printName(self, name):
        print(name)

A.printName("asd")

I get that error TypeError: printName() missing 1 required positional argument: 'name'. What i'm missing?

akerbeltz
  • 39
  • 1
  • 9

2 Answers2

3

You need to create a class instance and then call method on that instance:

class A:
    def printName(self, name):
        print(name)

class_instance = A()
class_instance.printName("asd")
Andrea
  • 583
  • 5
  • 15
0

This would work, using staticmethod if you want to call printName() without creating an instance of that class

class A:
    @staticmethod
    def printName(name):
        print(name)

A.printName('hello')
ksai
  • 987
  • 6
  • 18
  • Thanks for the answer. Can you explain what is a static method in python and why it dont need the 'self'?, I tried your code and it works even without the @staticmethod, why is that? Sorry for the amount of questions but i'm having a lot of trouble to understant how works the 'self' argument – akerbeltz Jul 11 '17 at 01:22
  • 1
    @akerbeltz:) **staticmethods** are methods that are bound to a class rather than its object. They don't need class instance`@staticmethod` tells we are using `staticmethod`. In earlier versions, the syntax to write **staticmethod** was different. You can just google for more information – ksai Jul 11 '17 at 01:27
  • self is an equivalent of, for 'this' object. staticmethod is not for different instances it is bound to a class. – gout Jul 11 '17 at 01:29
  • Thanks for the answers! you help me a lot. There's something i don't understand at all. When i write `A.printName('hello')` or `a=A.printName('hello')` i'm not creating an instance of the class A? – akerbeltz Jul 11 '17 at 01:42
  • @akerbeltz :) No, you are not creating instance in either way. You can create an instance like `instance_A = A()`. if the answer was helpful, please mark the answer as _accept_ answer. – ksai Jul 11 '17 at 02:43