oop - Python Passing a Function to an Object -


i trying create class allows users create custom button object, holds button's appearance attributes, function, want able run when call button's executefunction() command.

def foo():     print "bar"  class button(object):      def __init__(self, name, color, function):         self.name = name         self.color = color         self.function = function      # want able run function calling method     def executefunction(self):         self.function()  newbutton = button("example", red, foo()) newbutton.executefunction() 

is correct way, or there specific way perform kind of action?

in python, functions objects , can passed around. there small error in code , easy way simplify this.

the first problem calling function foo while passing in button class. pass result of foo() class, , not function itself. want pass foo.

the second nice thing can assign function instance variable called function (or executefunction if want), , can called via newbutton.function().

def foo():     print "bar"  class button(object):      def __init__(self, name, color, function):         self.name = name         self.color = color         self.function = function   newbutton = button("example", red, foo) newbutton.function() 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -