PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 7, 2022

[FIXED] How to Change a Class Instance's Method in Python?

 July 07, 2022     class, python     No comments   

Issue

I want to create a python library and part of the function of this library involves creating a class instance with some user defined variables. How do I let the user write their own conditionals for the class instance in said instance's method? For example, say I have an instance of the following class:

class Test:
    def __init__(self, some_value):
        self.some_value = some_value
    def func(self):
        pass

instance = Test(4)

How do I let a user change what instance.func() does (how can I let a user access the object's variables?


Solution

You could pass a reference to the user's function to init For example:

class Test:
    def __init__(self, user_function):
        self._function = user_function
    def func(self):
        return self._function()

def ufunc_1():
    return 'Hello world!'

def ufunc_2():
    return 'Goodbye cruel world'


t_1 = Test(ufunc_1)
t_2 = Test(ufunc_2)

print(t_1.func())
print(t_2.func())

In this way, the reference to the user function is stored in an instance variable.

Output:

Hello world!
Goodbye cruel world


Answered By - Stuart
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing