Attribute-Method Equivalence

From Jonathan Gardner's Tech Wiki
Jump to: navigation, search

The idea of Attribute-Method Equivalence is that an attribute and method are really the same thing, except methods are attributes that store functions.

This is present, more-or-less, in Python, but like other languages, there is a twist: methods are "bound" to the object calling it. That is, the method of an object has a memory of how the attribute was loaded. However, there is no such binding when you assign a function to an attribute of an object. IE, a = A(); a.foo = lambda: 12; a.foo()

In order for Attribute-Method Equivalence to be implemented, you would write special functions that vary their behavior based on the types of objects passed in rather than what object they were accessed through. However, it would eliminate the need for "self" or "this" since methods no longer belong to a class or an object.

For example, on the list object in Python there is a sort function, [1,2,3].sort() Note that when you call the method sort(), the list [1,2,3] is passed in as an invisible first parameter.

If we had attribute-method equivalence, then sort() wouldn't get this magical first parameter. You would have to pass it the list you wanted sorted instead, IE, [1,2,3].sort([1,2,3])

This is certainly more explicit, but it begs the question why have the sort method on the list at all? It would make sense to make a global sort() function that knows how to sort lists. It can be adapted to know how to sort other things as well.

If the programmer wants to modify the global sort() function so that it means something else when called with a different type of attribute, he would have to plug in to the sort() function the behavior, either by replacing it or by having the authors of sort() build a mechanism where modifications can be retroactively loaded in. For instance, the sort function itself could have a table of what function to call when various objects are invoked, or perhaps a list of functions that attempt to sort the item one after the other, using the result of the first one to claim that it did it properly. This sounds hacky and weird, but it is a very common practice in video games that allow modders to change the video game. It is also used in other areas such as DOM event processing.