Python Forum
User defined method as variable or argument
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
User defined method as variable or argument
#1
I'll try to communicate this as clearly as possible. I am still fairly new. Thanks in advance!

Here is my issue, in a nutshell:

I have created a custom class with methods and instantiated it successfully.
I have created a list containing these instances.

When I call the method explicitly by referencing objects in my list by index, everything works fine.

When I store the method in a variable and try to apply it the same way I get an error ("name 'describe' is not defined").

Ultimately, I am trying to pass this user created method as an argument of a function, but the result is the same error as above.

Below is the pseudocode, which I think is the best way to communicate my problem.
All help is appreciated. I will clarify as best as I can. Thanks for your patience, I am trying to digest quite a few concepts here.


# Create custom class

class MyClass:

def constructor():
statement
statement

def my_method():
statment
statement

# Create some instances of custom class

item1 = MyClass()
item2 = MyClass()
item3 = MyClass()

# Create a list containing the instances

my_list = [item1, item2, item2]


[# This works perfectly:

result = my_list[index].my_method()



# This does not work:
# (Error = name 'my_method' is not defined)


m = my_method()
result = my_list[index].m

# This throws the same error:

my_function(my_list, my_method)

# However, the following works exactly as desired (obviously I adjust the parameters in the function definition according to which approach I am trying):

my_function(my_list).my_method()
Reply
#2
Maybe I can express it more concisely:

I don't want to hard code which method (imported from another user made module) is called in my function. I want to be able to pass the object and method as arguments. The potential methods I am passing are already built into the objects.

Something like this:

Def the_function( object_arg, method_arg() ):
- - Do the thing.

And call it:

the_function( the_cheese, cut() )

'cut()' is already a method for 'the_cheese' object.

I have the sense that this is a very fundamental issue, perhaps related to scope, but I have not been able to figure it out or find answers online.
Reply
#3
This is evaluating of the method. Not saving method into the variable!

m = my_method()
This is few examples how to store method or call it from string variable:

class MyClass:
    def my_method(self):
        print("My method has been called")


my_object = MyClass()

# call 1 - storing method to the variable and then calling it
my_method = my_object.my_method
my_method()

# call 2 - calling method with name in string variable
method_name = "my_method"
getattr(my_object, method_name)()
Reply
#4
Thank you. I am working with what you've shown me and trying to find a solution.

Here is a cleaner example with actual code that replicates the error I am having:

# The class
class MyClass:
	# constructor
	def __init__(self):
		self.name = "a class"
		self.text = "I am for testing stuff."
		
	# One method
	def describe(self):
		print(self.name)
		print(self.text)

# An instance of 'MyClass'
my_obj = MyClass()
my_obj.name = "My Object"
my_obj.text = "I am a sample object, of the 'MyClass' class"


# Define simple function that takes an object and method as arguments
def my_function(the_object, the_method):
	the_object.the_method()
	
	
# Call the function with args
my_function(my_obj, describe)

"""
NameError: name 'describe' is not defined
"""
Reply
#5
You must fix the end of the script a little bit to get it work:

# Define simple function that takes an object and method as arguments
def my_function(the_object, the_method):
    getattr(the_object, the_method)()


# Call the function with args
my_function(my_obj, "describe")
You called my_function with the describe variable which hasn't been defined. And inside my_function you called the method also bad. You must get the object method with getattr(object, name_of_the_method) and then call it with () - so getattr(object, name_of_the_method)()
Reply
#6
Thank you very much! I understand much better, now.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Variable not defined even though it is CoderMerv 2 50 1 hour ago
Last Post: CoderMerv
  Variable is not defined error when trying to use my custom function code fnafgamer239 4 511 Nov-23-2023, 02:53 PM
Last Post: rob101
  Printing the variable from defined function jws 7 1,160 Sep-03-2023, 03:22 PM
Last Post: deanhystad
Information How to take url in telegram bot user input and put it as an argument in a function? askfriends 0 1,026 Dec-25-2022, 03:00 PM
Last Post: askfriends
  i want to use type= as a function/method keyword argument Skaperen 9 1,771 Nov-06-2022, 04:28 AM
Last Post: Skaperen
  User-defined function to reset variables? Mark17 3 1,587 May-25-2022, 07:22 PM
Last Post: Gribouillis
  Multiple user defined plots with secondary axes using for loop maltp 1 1,393 Apr-30-2022, 10:19 AM
Last Post: maltp
  [variable] is not defined error arises despite variable being defined TheTypicalDoge 4 2,040 Apr-05-2022, 04:55 AM
Last Post: deanhystad
Question How to pass a method as argument in an another method? anilanvesh 6 2,663 Sep-30-2021, 10:18 PM
Last Post: deanhystad
  [solved] Variable number of dictionnaries as argument in def() paul18fr 11 6,024 Apr-20-2021, 11:15 AM
Last Post: paul18fr

Forum Jump:

User Panel Messages

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