Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning method to object at runtime in Python

I'm trying to do the Javascript equivalent in Python:

a.new_func = function(arg1, arg2) {
    var diff = arg1 - arg2;
    return diff * diff;
}

Right now, the way I'm doing this is by defining the method first, and then assigning it, but my question is whether or not Python allows a shorthand to do the assigning and the defining part in the same line. Something like this:

a.new_func = def new_func(arg1, arg2):
    diff = arg1 - arg2
    return diff * diff

Instead of this:

def new_func(arg1, arg2):
    diff = arg1 - arg2
    return diff * diff
a.new_func = new_func

I realize the difference is not major, but am still interested to know whether or not it's possible.

like image 753
smaili Avatar asked Dec 04 '22 07:12

smaili


1 Answers

Python supports no such syntax.

I suppose if you wanted, you could write a decorator. It might look a bit nicer:

def method_of(instance):
    def method_adder(function):
        setattr(instance, function.__name__, function)
        return function
    return method_adder

@method_of(a)
def new_func(arg1, arg2):
    stuff()

Or if you want the method to have access to self:

def method_of(instance):
    def method_adder(function):
        setattr(instance, function.__name__, function.__get__(instance))
        return function
    return method_adder

@method_of(a)
def new_func(self, arg1, arg2):
    stuff()
like image 180
user2357112 supports Monica Avatar answered Dec 08 '22 04:12

user2357112 supports Monica