1

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?

1
  • 2
    Why are you trying to call an instance method on the class, and where's your self parameter? Frankly, there seems to be no point these methods being in a class at all. Commented Jun 24, 2015 at 8:03

1 Answer 1

1

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")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.