Assigning functions as attributes of an object, and then calling without an implied β€œI” argument?

Python allows you to assign a given function to a class as an attribute, e.g.

def fish_slap(fish):
    # do something

class dance(object):
    dance_move=fish_slap

However, if we try to say

d=dance()
d.dance_move("Halibut")

we get the following error:

TypeError: fish_slap() takes exactly 1 arguement (2 given)

Python seems to consider this as an object method and provides an implied self argument. Fairly enough, it seems that I just found out that assigning a function as an attribute in this way is equivalent to defining a function directly inside the class. I see that this is a useful feature.

, . , , "" . , , ( ) . :

def RMSE(predicted,observed):
    "Root mean squared error"
    return sp.sqrt(sp.mean((predicted-observed)**2))

SciPy sp. .py , , , "".

, , , ,

some_model=SomeModel(initial_parameter_values_guess) 
some_model.objective_function = RMSE
some_model.train(training_data)
predictions_RMSE = some_model.predict()
some_mode.objective_function = MAE
predictions_MAE = some_model.predict()

, , , , , , / , .

- , ?

, python2 python3. , , . python2, matplotlib, , python3, .

+5
1

staticmethod

class dance(object):
    dance_move=staticmethod(fish_slap)

, staticmethod, :

>>> def move():
...     print "disco party!"
... 
>>> class dance(object):
...     dance_move = staticmethod(move)
... 
>>> d = dance()
>>> d.dance_move()
disco party!
>>> d.break_it_down = move
>>> d.break_it_down()
disco party!
+8

All Articles