2 ms·
Placing 'self' in the parameter list allows external procedures to be monkey-patched into a class, without needing to wrap it up in a 'partial'. For example:
by jmillikin 17y ago
Placing 'self' in the parameter list allows external procedures to be monkey-patched into a class, without needing to wrap it up in a 'partial'. For example:
def foo(self, x):
self.bar(x, 42)
class MyClass:
def bar(self, x, y):
print ("%s %s" % (x, y))
MyClass.foo = foo
While this is ugly, there are times when augmenting (or replacing) a class's existing methods is useful.
- sonoffett 17y agoI have found it very useful when writing unit tests for a particular method. I don't have to instantiate the class for which the method is a member of; instead I can easily pass a mock object as self that only contains the properties the method is supposed to test. Furthermore the claim that python doesn't support objects cleanly or easily is unfounded: 1) everything is an object in python (http://diveintopython.org/getting_to_know_python/everything_is_an_object.html http://diveintopython.org/getting_to_know_python/everything_...), including classes. 2) properties of an object are accessed in just the same way as in Java (obj.property), I don't understand where the confusion lies.
- anamax 17y agothe def self.foo(x): syntax does not interfere with such monkey patching because it gets turned into foo = {fn using (self, x)}.