473,411 Members | 1,899 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,411 software developers and data experts.

New style classes and rich comparison

Could anyone explain to me why this does not work as intended?
class Oldstyle: .... pass
.... old = Oldstyle()
old == 1 False old.__eq__ = lambda x: True
old == 1 True

Nice and fine.

newbie = Newstyle()
newbie == 1 False newbie.__eq__ = lambda x: True
newbie == 1 False

Doesn't work!
It seems that __eq__ is fetched directly from newbie's class, not from
newbie.
Newstyle.__eq__ = lambda self, x: True
newbie == 1 True

Adding a method __getattribute__ that prints the key and then calls
object.__getattribute__ proves this - nothing is printed for comparison.

This goes even for hash():
newbie.__hash__ = lambda x: 1337
hash(newbie) 1077345744 Newstyle.__hash__ = lambda x: 15
hash(newbie) 15

Why is this? Where is this documented?

Here's my real goal, to create a Dummy class that supports anything:

from dummy.py:

class Dummy(object):
"""An object that can do anything in the world"""
def __call__(self, *args, **kwargs):
"""Can be called with any kind of parameters, returns
a new Dummy."""
return Dummy()
def __getattribute__(self, key):
"""Any attribute created and stored on demand. All
attributes are new Dummys."""
try:
value = object.__getattribute__(self, key)
except AttributeError:
value = self()
# remember it to next time! =)
setattr(self, key, value)
return value

This dummy can be used for many things:
from dummy import Dummy
a = Dummy()
a.b <dummy.Dummy object at 0x81e02dc> a.b == a.b 1 a.b == a 0 c = a.b.anything(123)
c.dot.something <dummy.Dummy object at 0x81f3764>
Now the trouble is that __operator__ is not resolved as I would expect.
a.__add__(a) <dummy.Dummy object at 0x81ad4dc> a + a Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand types for +: 'Dummy' and 'Dummy'
Why are operators looked up in the class instead of the object? How
can I modify my Dummy class to return 'anything' even directly in the
class?

Ie. what I probably want is something like this (simulated):
Dummy.asdads

<dummy.Dummy object at 0x81ad4dc>

That way Dummy.__add__ would return a new Dummy instance, and
Dummy() + Dummy() would work as expected.

My first attempt was to manually define different __operator__-methods
in the dummy, but this got rather boring. Can I use __metaclass__ or
something?
--
Stian Søiland Being able to break security doesn't make
Trondheim, Norway you a hacker more than being able to hotwire
http://stain.portveien.to/ cars makes you an automotive engineer. [ESR]
Jul 18 '05 #1
3 1344
Stian Søiland wrote:
newbie.__hash__ = lambda x: 1337
hash(newbie) 1077345744 Newstyle.__hash__ = lambda x: 15
hash(newbie)

15

Why is this?


Consider:

class A(object):
def __hash__(self): return 5
print hash(A) # Which function should this call?
--
Rainer Deyke - ra*****@eldwood.com - http://eldwood.com
Jul 18 '05 #2
* Rainer Deyke spake thusly:
Consider:

class A(object):
def __hash__(self): return 5
print hash(A) # Which function should this call?


The hash method of A's class, ie. A.__class__.__hash__, usually
type.__hash__.

Hmmm. I think I get your point. hash and cmp and so on should call
A.__class__.hash(A) to be generic enough.

It's still confusing.. =) And how should I resolve this issue with my
Dummy class? (it's ok for the Dummy class itself to be a Dummy, but it
didn't work well to make Dummy = Dummy())

--
Stian Søiland Being able to break security doesn't make
Trondheim, Norway you a hacker more than being able to hotwire
http://stain.portveien.to/ cars makes you an automotive engineer. [ESR]
Jul 18 '05 #3
st***@stud.ntnu.no (Stian Søiland) writes:
Could anyone explain to me why this does not work as intended?
[snippo]
It seems that __eq__ is fetched directly from newbie's class, not from
newbie.
Yup! One of the differences between new-style and old-style classes.

To see why something has to be a bit like this, consider the
difference between a unbound method for the instance and a bound
method for the *type* of the instance...

[biggo snippo]
Can I use __metaclass__ or something?


I think that's what you want, yes.

Cheers,
mwh

--
Ignoring the rules in the FAQ: 1" slice in spleen and prevention
of immediate medical care.
-- Mark C. Langston, asr
Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

35
by: wired | last post by:
Hi, I've just taught myself C++, so I haven't learnt much about style or the like from any single source, and I'm quite styleless as a result. But at the same time, I really want nice code and I...
7
by: Rob Nicholson | last post by:
We're using a well known presentation layer library to implement complex controls on an intranet site. IE has the following limitation which effectively means that you can only have 30 <STYLE> tags...
5
by: Jon Guyer | last post by:
>>> This is a fake line to confuse the stupid top-posting filter at gmane We have a rather complicated class that, under certain circumstances, knows that it cannot perform various arithmetic...
0
by: fiona | last post by:
Divelements release fully featured Office 2007 style Ribbon control Major component suite designed to mimic the advanced user interface features of Microsoft Office 2007 Dorset, United Kingdom -...
11
by: Steven D'Aprano | last post by:
I'm writing a class that implements rich comparisons, and I find myself writing a lot of very similar code. If the calculation is short and simple, I do something like this: class Parrot: def...
5
by: =?Utf-8?B?UmljaA==?= | last post by:
Greetings, I am actually a VB.Net guy, but I have worked somewhat with C++ and C#. I just want to ask about the relationship between Abstract Classes and Interfaces. My first question is if...
3
by: Riccardo Murri | last post by:
Hello, I have some code that stops when trying to find a graph in a list of similar graphs:: (Pydb) list 110 try: 111 canonical = self.base 112 except ValueError: 113 ...
11
by: allendowney | last post by:
Hi All, I am working on a revised edition of How To Think Like a Computer Scientist, which is going to be called Think Python. It will be published by Cambridge University Press, but there...
0
by: Gabriel Genellina | last post by:
En Thu, 10 Jul 2008 17:37:42 -0300, Ethan Furman <ethan@stoneleaf.us> escribi�: If your objects obey the trichotomy law (an object MUST BE less than, greater than, or equal to another one,...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.