Python Forum
Building a method name in a function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Building a method name in a function
#1
Hi,
as an almost beginner, this is just a general knowledge question.
Let's say i have a class foo defining method1, method2, method3.
I'd like to have a function outside class foo, for example:
my_function(fooinstance,name,num),
and build the fooinstance method name by name+num, and then call fooinstance.(name+num).

I'd like to avoid bunch of tests of the kind:
if name==method and num==1: fooinstance.method1()

Is such behavior possible ? Otherwise, gotta code those 40 if..elif i want to avoid.

thanks
Reply
#2
I'm not sure if you can come up with function names that way but you could put your methods in a list and just loop through the list like

methods=[method1, method2, method3]

for i in range(len(methods)):
    Do your check here 
    
I'm not entirely sure if that's what you're looking for but hope it helps
Reply
#3
i guess it's basically the same as i would have to access them as foo.methods[0] and foo objects will have no attribute methods.

i still will have to test i in order to call foo.method1, foo.methods[1] will return no attribute error.
Reply
#4
(Oct-18-2020, 10:55 PM)ffgth Wrote: i guess it's basically the same as i would have to access them as foo.methods[0] and foo objects will have no attribute methods.

i still will have to test i in order to call foo.method1, foo.methods[1] will return no attribute error.

Try
foo.method[1]()

Just use the empty brackets at the end when you need to call the method.
Reply
#5
Look at getattr() built-in function.
Note that with attribute name like method1, method2, etc. there is good chance you are doing something the wrong way. Better tell us what/why you are doing this and what's your code, i.e. instead of 40 methods 2 or 3 will be sufficient to demonstrate your case.
ndc85430 likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
If you think of a Python class as a dictionary you have a pretty accurate picture of how it works. When I do a "def method_name" inside the class it adds "method_name" to a dictionary in the class with a value that is the class.method_name function. Creating a class variable does the same thing, except the value in the dictionary is the object referenced by the class variable name.

Since classes are essentially dictionaries with some syntactic sugar, you can add methods from anywhere and at any time. You can also add methods to instances of classes so that two instances do different things when the same method name is used. This is usually a bad idea, but there are times when it can be useful.

I don't know what you are trying to do, but here is something I did which may be similar. I have a class named Model. A model is a collection of models/parts. I have no idea what parts a model may contain or what those parts can do, but I commonly ask all a model's parts to do the same thing. For this I use "forall".
    def forall(self, func_name, *args, **kwargs):
        """Have all my parts execute the named function"""
        for part in self._parts:
            if (func := getattr(part, func_name, None)) is not None:
                func(part, *args, **kwargs)
        return self
Reply
#7
(Oct-19-2020, 03:27 AM)buran Wrote: Look at getattr() built-in function.
Note that with attribute name like method1, method2, etc. there is good chance you are doing something the wrong way. Better tell us what/why you are doing this and what's your code, i.e. instead of 40 methods 2 or 3 will be sufficient to demonstrate your case.

getattr may do the job, basically I got 40 Custom GraphviewWidget that are in a ui class for diaplaying resources of a n servers (CPU, RAM, load average, I/O, etc..). All these are embedded in a TabWidget, and i have to display Server_Name_Resource_method in each tab.
Design is probably not best but simple :)

Thanks anyway for your answers, will test getattr at once.
Reply
#8
I think you need one method and it should take argument (i.e. which widget), not have separate method for each widget (which in turn you will try to call). Note, the widgets should also be in some sort of container, not stored in separate variables/names (you are unclear as to that part)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#9
indeed, i'm accessing the attributes (and not the methods) generated through Qt designer. gettattr did the job and saved me 40 conditions :)
Reply
#10
(Oct-19-2020, 01:01 PM)ffgth Wrote: i'm accessing the attributes (and not the methods)

attributes
sometimes are grouped into/referred to as properties and methods. So all methods are attributes but not all attributes are methods.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Building a DoublyLinkedList in Python - - append method Drone4four 2 371 Jan-08-2024, 01:27 PM
Last Post: Drone4four
  i want to use type= as a function/method keyword argument Skaperen 9 1,771 Nov-06-2022, 04:28 AM
Last Post: Skaperen
  function/method help myv5285 3 2,741 May-17-2020, 04:19 AM
Last Post: buran
  Accessing method as function object ClassicalSoul 2 1,975 Feb-14-2020, 09:31 PM
Last Post: wavic
  got SyntaxError while building simple function zarize 2 2,078 Feb-14-2020, 10:51 AM
Last Post: zarize
  function vs method prateekshaw 2 2,152 Nov-14-2019, 07:00 PM
Last Post: DeaD_EyE
  I'm trying to figure out whether this is a method or function call 357mag 2 2,378 Jul-04-2019, 01:43 AM
Last Post: ichabod801
  function method problems drchar 2 2,854 Dec-11-2018, 02:38 PM
Last Post: buran
  Understanding Method/Function robdhunter 2 2,611 Mar-10-2018, 11:57 PM
Last Post: robdhunter
  How to pass value from method to function iFunKtion 11 8,710 May-23-2017, 05:06 PM
Last Post: iFunKtion

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020