0

I am attempting to use a dict to control function selection from within a class, however, I get this following TypeError:

TypeError: A() missing 1 required positional argument: 'self'

Example code:

class Tt:
    def __init__(self):
        pass
    def A(self):
        print("a")
    def B(self):
        print("b")
    def C(self):
        print("c")

    a_diction={
         '0' : A,
         '1' : B,
         '2' : C
    }

    def ad(self,data):
        self.a_diction[data]()

How should I construct this switch in ad to provide self to both a_diction and to the called method A, B and C?

0

2 Answers 2

3

The error message indicates that you're missing an argument. I suggest adding an argument.

self.a_diction[data](self)
Sign up to request clarification or add additional context in comments.

3 Comments

yes, this works.... but why did it work? logically it should have been self.(self.a_diction[data])() .. which is wrong i know.. but passing self as an argument here works.. why so?
@user3007395 can you post your actual code in the question? The code that is there as it stands will not work, even with this addition.
It works because someObject.method() can also be called using the syntax someClass.method(someObject). Similarly, self.thing() and thing(self) both work.
1

Could you do the following instead?

class Tt:
    def __init__(self):
        self.a_diction = {
             0: self.A,
             1: self.B,
             2: self.C
        }

    def A(self):
        print("a")

    def B(self):
        print("b")

    def C(self):
        print("c")

    def ad(self,data):
        self.a_diction[data]()

I.e., make a_diction an instance attribute and initialize it in __init__? Then you can choose bound methods as values in the dictionary instead of unbound methods.

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.