Python Forum
[Classes] Class Intermediate: Operator Overloading
Thread Rating:
  • 2 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Classes] Class Intermediate: Operator Overloading
#4
So what else can we override? Lots of stuff. I'm going to assume you have a grasp of the basic idea of operator overloading, and talk about some of the other special methods for operator overloading. The ones I'm not going to talk about get into the nuts and bolts of Python. If you mess with them without knowing what you are doing, you can totally screw things up. If you want to screw things up, or want more details on the special methods I've talked about, go to the Data Model section of the Language Reference section of the documentation for your version of Python.

In addition to __repr__ and __str__ there are also __bytes__ and __format__. __bytes__ is called when bytes(a) is used to make a byte-string representation of an object, and should return a bytes object. __format__ is called when string formatting (''.format()) is called. It receives a format specification as a parameter, and allows you to customize how string formatting is performed on your object. For example, if some numeric formatting specifying a number of digits was passed to __format__, you could apply that formatting to the x and y attributes of your Vector object.

__hash__ is called by the built-in function hash(). It should return an integer, and if two instances of your class evaluate as equal, they must return the same integer. This is very useful, because implementing it allows your objects to be used in sets and frozensets, and as keys in dicts. A good way to use it in the Vector class would be to return hash((x, y)), making use of the tuple class's hashing function.

__bool__ is called whenever your object is used for truth testing. For Vector we might say it returns False for (0, 0), and True for everything else. If __bool__ is not implemented, __len__ is called, and the object is True if __len__ returns a non-zero value. If neither is implemented, True is returned.

One of my favorite special methods is __call__. Don't ask me why. It allows instances to act like functions. For example, say we implemented __call__ for our Vector class. Then we made an instance with 'a = Vector(8, 1)'. Then 'a('spam', 'eggs')' would call 'a.__call__(self, 'spam', 'eggs')'.

There are several methods for making objects that act as containers. When doing that you should also add the methods the container type you are emulating generally has, such as append and index for sequences and get for dictionaries. Also take a look at the collections modules, it provides some base classes that are useful for emulating containers. The basics are (assuming an instance named foo):

__len__ overrides len(foo)
__getitem__(key) overrides foo[key]
__setitem__(key, value) overrides foo[key] = value
__delitem__(key) overrides del foo[key]
__iter__() overrides making an iterator of the object
__reversed__() overrides reversed(foo)
__contains__(value) overrides value in foo
For making things that act like numbers I skipped over __divmod__, which overrides the divmod() built-in function. Also note that __pow__ overrides both a ** x and the pow built-in function. In addition to the __add__ and __radd__ type methods for mathematical operators, there is also __iadd__, __isub__, __imul__, and so on. These override augmented assignements such as +=, -=, and *=. If you don't define them, Python just converts 'a += b' to 'a = a + b', but this may not be the functionality you are looking for. For unary +, -, and ~ use the __neg__, __pos__, and __inv__ methods. For overriding abs() and round() use __abs__ and __round__. For converting to numbers, use __int__, __float__, __complex__.

I hope this massive summary impresses upon you can do with operator overloading, and how much you can mess up with operator overloading. So go forth and be careful.

And remember that it's not my fault. [Image: icon_e_wink.gif]
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures


Messages In This Thread
RE: Class Intermediate: Operator Overloading - by ichabod801 - Sep-15-2016, 11:07 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [Classes] Class Intermediate: Inheritance ichabod801 2 9,508 Sep-15-2016, 11:25 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020