user4989939
user4989939

Reputation: 349

Python instance methods vs static methods

I try to learn Python 2.7. When i run this code:

class MyClass:
    def PrintList1(*args):
        for Count, Item in enumerate(args):
            print("{0}. {1}".format(Count, Item))

    def PrintList2(**kwargs):
        for Name, Value in kwargs.items():
            print("{0} likes {1}".format(Name, Value))

MyClass.PrintList1("Red", "Blue", "Green")
MyClass.PrintList2(George="Red", Sue="Blue",Zarah="Green") 

i get a TypeError:

MyClass.PrintList1("Red", "Blue", "Green")
TypeError: unbound method PrintList1() must be called with MyClass instance    as first argument (got str instance instead)
>>> 

Why?

Upvotes: 1

Views: 53

Answers (1)

firelynx
firelynx

Reputation: 32244

MyClass is, a class.

PrintList1 is a method.

Methods needs to be called on instanciated objects of the class.

Like this:

myObject = MyClass()
myObject.PrintList1("Red", "Blue", "Green")
myObject.PrintList2(George="Red", Sue="Blue", Zarah="Green")

For this to work properly, you also need to make your methods take the self argument, like this:

class MyClass:
    def PrintList1(self, *args):
        for Count, Item in enumerate(args):
            print("{0}. {1}".format(Count, Item))

    def PrintList2(self, **kwargs):
        for Name, Value in kwargs.items():
            print("{0} likes {1}".format(Name, Value))

If you want to call your code as static functions, you need to add the staticmethod decorator to your class, like this:

class MyClass:
    @staticmethod
    def PrintList1(*args):
        for Count, Item in enumerate(args):
            print("{0}. {1}".format(Count, Item))

    @staticmethod
    def PrintList2(**kwargs):
        for Name, Value in kwargs.items():
            print("{0} likes {1}".format(Name, Value))

MyClass.PrintList1("Red", "Blue", "Green")
MyClass.PrintList2(George="Red", Sue="Blue",Zarah="Green")

Upvotes: 1

Related Questions