Defining "Method_Called".. How to Make a Hook Method Which Gets Called Every Time Any Function of a Class Gets Called

Defining method_called.. How do I make a hook method which gets called every time any function of a class gets called?

Take a look at Kernel#set_trace_func. It lets you specify a proc which is invoked whenever an event (such as a method call) occurs. Here's an example:

class Base
def a
puts "in method a"
end

def b
puts "in method b"
end
end

set_trace_func proc { |event, file, line, id, binding, classname|
# only interested in events of type 'call' (Ruby method calls)
# see the docs for set_trace_func for other supported event types
puts "#{classname} #{id} called" if event == 'call'
}

b = Base.new
b.a
b.b

Outputs:

Base a called
in method a
Base b called
in method b

How to execute a function before and after each class method call?

Here is a rough solution to the problem:

// we iterate over all method names
Object.getOwnPropertyNames(Foo.prototype).forEach((name) => {

// First to do: we save the original method. Adding it to prototype
// is a good idea, we keep 'method1' as '_method1' and so on
Foo.prototype['_' + name] = Foo.prototype[name];

// Next, we replace the original method with one that does the logging
// before and after method execution.
Foo.prototype[name] = function() {

// all arguments that the method receives are in the 'arguments' object
console.log(`Method call: method1(${Object.values(arguments).join(', ')})`);

// now we call the original method, _method1, on this with all arguments we received
// this is probably the most confusing line of code here ;)
// (I never user this['method'] before - but it works)
const result = this['_' + name](...arguments);

// here is the post-execution logging
console.log(`Method result: ${result}`);

// and we need to return the original result of the method
return result;
};
});

Please note that this code is not part of the class itself, execute it as a normal script.

And there is a good chance that this short proof of concept crashes on real-world classes and requires some additional checks and special-case handlers, especially to get proper logging output. But it works with you Foo class.

Here's the working example: https://codesandbox.io/s/great-fog-c803c

Python class method run when another method is invoked

No, there are no hooks on a class to do this. Methods are attributes too, albeit somewhat special in that they are produced when accessing the function object on the instance; functions are descriptors.

The call to a method object is then a separate step from producing the method object:

>>> class Foo(object):
... def bar(self):
... return 'bar method on Foo'
...
>>> f = Foo()
>>> f.bar
<bound method Foo.bar of <__main__.Foo object at 0x100777bd0>>
>>> f.bar is f.bar
False
>>> stored = f.bar
>>> stored()
'bar method on Foo'

It is the task of the object.__getattribute__() method to invoke the descriptor protocol, so you could hook into that to see when a method is produced, but you'd still need to wrap that produced method object to detect calls. You could return an object with a __call__ method that proxies for the actual method for example.

However, it'd be easier to decorate each method with a decorator that increments a counter every time it is called. Take into account decorators apply to a function before it is bound, so you'll have to pass self along:

from functools import wraps

def method_counter(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
self.methodCalls += 1
return func(self, *args, **kwargs)
return wrapper

You'd still need to apply this to all functions in your class. You could apply this manually to all methods you want to count:

class MyClass(object):
def __init__(self):
self.foo = "foo"
self.bar = "bar"
self.methodCalls = 0 #tracks number of times any function method is run

@method_counter
def get_foo(self):
return self.foo

@method_counter
def get_bar(self):
return self.bar

or you could use a metaclass:

import types

class MethodCounterMeta(type):
def __new__(mcls, name, bases, body):
# create new class object
for name, obj in body.items():
if name[:2] == name[-2:] == '__':
# skip special method names like __init__
continue
if isinstance(obj, types.FunctionType):
# decorate all functions
body[name] = method_counter(obj)
return super(MethodCounterMeta, mcls).__new__(mcls, name, bases, body)

def __call__(cls, *args, **kwargs):
# create a new instance for this class
# add in `methodCalls` attribute
instance = super(MethodCounterMeta, cls).__call__(*args, **kwargs)
instance.methodCalls = 0
return instance

This takes care of everything the decorator needs, setting a methodCalls attribute for you, so your class doesn't have to:

class MyClass(object):
__metaclass__ = MethodCounterMeta
def __init__(self):
self.foo = "foo"
self.bar = "bar"

def get_foo(self):
return self.foo

def get_bar(self):
return self.bar

Demo of the latter approach:

>>> class MyClass(object):
... __metaclass__ = MethodCounterMeta
... def __init__(self):
... self.foo = "foo"
... self.bar = "bar"
... def get_foo(self):
... return self.foo
... def get_bar(self):
... return self.bar
...
>>> instance = MyClass()
>>> instance.get_foo()
'foo'
>>> instance.get_bar()
'bar'
>>> instance.methodCalls
2

The above metaclass only considers function objects (so the result of def statements and lambda expressions) part of the class body for decoration. It ignores any other callable objects (there are more types that have a __call__ method, such as functools.partial objects), as are functions added to the class later on.

Is there a way to do some pre-process/post-process every time I call a function in python

This is typically done with a context manager.

import contextlib

@contextlib.contextmanager
def with_preparation():
prepare()
yield
done()

with preparation():
xyz.foo(<args>)

with preparation():
xyz.bar(<args>)

with preparation():
xyz.foobar()

preparation defines a function that returns a context manager. The with statement works by invoking the context manager's __enter__ method, then executing the body, then ensuring that the context manager's __exit__ method is invoked before moving on (whether due to an exception being raised or the body completing normally).

contextlib.contextmanager provides a simple way to define a context manager using a generator function, rather than making you define a class with explicit __enter__ and __exit__ methods.


You mentioned you need this for every function in a particular module. Without exact details about the module, this may not be entirely correct, but you might be able to build up on it.

class XYZWrapper:
def __getattr__(self, name):
# Intentionally let an AttributeError propagate upwards
f = getattr(xyz, name)
def _(self, *args, **kwargs):
prepare()
return f(*args, **kwargs)
done()
setattr(XYZWrapper, name, _)
return _

prepared = XYZWrapper()

prepared.foo(<args>)
prepared.bar(<args>)
prepared.foobar()


In short, any attribute access on the XYZWrapper instance tries to find an identical attribute on the xyz module, and if successful, defines a wrapper that calls prepare() and done() as needed and patches the XYZWrapper instance with the new wrapper.

Python calling method in class

The first argument of all methods is usually called self. It refers to the instance for which the method is being called.

Let's say you have:

class A(object):
def foo(self):
print 'Foo'

def bar(self, an_argument):
print 'Bar', an_argument

Then, doing:

a = A()
a.foo() #prints 'Foo'
a.bar('Arg!') #prints 'Bar Arg!'

There's nothing special about this being called self, you could do the following:

class B(object):
def foo(self):
print 'Foo'

def bar(this_object):
this_object.foo()

Then, doing:

b = B()
b.bar() # prints 'Foo'

In your specific case:

dangerous_device = MissileDevice(some_battery)
dangerous_device.move(dangerous_device.RIGHT)

(As suggested in comments MissileDevice.RIGHT could be more appropriate here!)

You could declare all your constants at module level though, so you could do:

dangerous_device.move(RIGHT)

This, however, is going to depend on how you want your code to be organized!

Is there a way to tell if `method_missing` was explicitly called?

Unlike initialize, which is invoked explicitly via the Class#new, the BasicObject#method_missing is invoked by the Ruby interpreter:

Invoked by Ruby when obj is sent a message it cannot handle. symbol is
the symbol for the method called, and args are any arguments that were
passed to it. By default, the interpreter raises an error when this
method is called. However, it is possible to override the method to
provide more dynamic behavior.

Kernel#caller will not include those locations in the execution stack trace from where Ruby interpreter invoked the method_missing if that's what you are looking for.

Call child method from parent

First off, let me express that this is generally not the way to go about things in React land. Usually what you want to do is pass down functionality to children in props, and pass up notifications from children in events (or better yet: dispatch).

But if you must expose an imperative method on a child component, you can use refs. Remember this is an escape hatch and usually indicates a better design is available.

Previously, refs were only supported for Class-based components.
With the advent of React Hooks, that's no longer the case

Modern React with Hooks (v16.8+)

const { forwardRef, useRef, useImperativeHandle } = React;

// We need to wrap component in `forwardRef` in order to gain
// access to the ref object that is assigned using the `ref` prop.
// This ref is passed as the second parameter to the function component.
const Child = forwardRef((props, ref) => {

// The component instance will be extended
// with whatever you return from the callback passed
// as the second argument
useImperativeHandle(ref, () => ({

getAlert() {
alert("getAlert from Child");
}

}));

return <h1>Hi</h1>;
});

const Parent = () => {
// In order to gain access to the child component instance,
// you need to assign it to a `ref`, so we call `useRef()` to get one
const childRef = useRef();

return (
<div>
<Child ref={childRef} />
<button onClick={() => childRef.current.getAlert()}>Click</button>
</div>
);
};

ReactDOM.render(
<Parent />,
document.getElementById('root')
);
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

<div id="root"></div>

call method in one stateful widget from another stateful widget - Flutter

To call a function of a parent, you can use the callback pattern. In this example, a function (onColorSelected) is passed to the child. The child calls the function when a button is pressed:

import 'package:flutter/material.dart';

class Parent extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return ParentState();
}
}

class ParentState extends State<Parent> {
Color selectedColor = Colors.grey;

@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(
color: selectedColor,
height: 200.0,
),
ColorPicker(
onColorSelect: (Color color) {
setState(() {
selectedColor = color;
});
},
)
],
);
}
}

class ColorPicker extends StatelessWidget {
const ColorPicker({this.onColorSelect});

final ColorCallback onColorSelect;

@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
RaisedButton(
child: Text('red'),
color: Colors.red,
onPressed: () {
onColorSelect(Colors.red);
},
),
RaisedButton(
child: Text('green'),
color: Colors.green,
onPressed: () {
onColorSelect(Colors.green);
},
),
RaisedButton(
child: Text('blue'),
color: Colors.blue,
onPressed: () {
onColorSelect(Colors.blue);
},
)
],
);
}
}

typedef ColorCallback = void Function(Color color);

Internal Flutter widgets like buttons or form fields use exactly the same pattern. If you only want to call a function without any arguments, you can use the VoidCallback type instead defining your own callback type.


If you want to notify a higher up parent, you can just repeat this pattern on every hierarchy level:

class ColorPickerWrapper extends StatelessWidget {
const ColorPickerWrapper({this.onColorSelect});

final ColorCallback onColorSelect;

@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(20.0),
child: ColorPicker(onColorSelect: onColorSelect),
)
}
}

Calling a method of child widget from a parent widget is discouraged in Flutter. Instead, Flutter encourages you to pass down the state of a child as constructor parameters. Instead of calling a method of the child, you just call setState in the parent widget to update its children.


One alternative approach are the controller classes in Flutter (ScrollController, AnimationController, ...). These are also passed to the children as constructor parameters, and they contain methods to control the state of the child without calling setState on the parent. Example:

scrollController.animateTo(200.0, duration: Duration(seconds: 1), curve: Curves.easeInOut);

The children are then required to listen to these changes to update their internal state. Of course, you can also implement your own controller class. If you need to, I recommend you to look at the source code of Flutter to understand how that works.


Futures and streams are another alternative to pass down state, and could also be used to call a function of a child.

But I really don't recommend it. If you need to call a method of a child widget, it is very like that your application architecture is flawed. Try to move the state up to the common ancestor!

Calling method inside of mouse hook code causes access violation

What you describe suggests that your global MainForm pointer is not pointing at a valid Form object when the hook is called. Any call to a method of the form, such as MouseHook(), will thus have an invalid this pointer. You must make sure you are assigning that pointer.

You are using the SetWindowsHookEx() example that I gave you in answer to another question. In that same answer, I had also given you an alternative solution that did not involve SetWindowsHookEx() - handling the WM_INPUT message from the RAW Input API. Your question did not mention that you are using FireMonkey instead of VCL. The example I had given you was for VCL. I have now updated that answer to include a FireMonkey example as well.

When is the finalize() method called in Java?

In general it's best not to rely on finalize() to do any cleaning up etc.

According to the Javadoc (which it would be worth reading), it is:

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

As Joachim pointed out, this may never happen in the life of a program if the object is always accessible.

Also, the garbage collector is not guaranteed to run at any specific time. In general, what I'm trying to say is finalize() is probably not the best method to use in general unless there's something specific you need it for.



Related Topics



Leave a reply



Submit