473,769 Members | 2,100 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.__getatt ribute__ 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.__getatt ribute__(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(12 3)
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 1368
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__.__h ash__, usually
type.__hash__.

Hmmm. I think I get your point. hash and cmp and so on should call
A.__class__.has h(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
4548
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 go to great lengths to restructure my code just to look concise and make it more manageable. When I say this, I'm also referring to the way I write my functions. It seems to me sometimes that I shouldn't have many void functions accepting...
7
1481
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 per page. That's in effect 30 style sheets per page, not classes - each sheet can have as many style classes as you want. http://support.microsoft.com/default.aspx?scid=kb;en-us;262161 Unfortunately, this presentation library generates...
5
1561
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 operations, and so returns NotImplemented. As a trivial example: >>> class my: ... def __mul__(self, other): ... return NotImplemented ...
0
1556
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 - September 4 2006, Divelements Ltd announces the release of SandRibbon V1. SandRibbon is a suite of controls and components that present your application's commands and features in well-organised lists and popups, divided into logical groups with...
11
1597
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 __eq__(self, other): return self.plumage() == other.plumage() def __ne__(self, other): return self.plumage() != other.plumage()
5
3019
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 C# even has Iinterfaces. I took some Java programming classes and Interfaces are a main staple of Java. And in VB.Net I use interfaces for setting up definitions of classes. I am guessing that Abstract classes in C# do the same thing as...
3
2420
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 raise ValueError, \
11
1446
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 will still be a free version under the GNU FDL. You can see the latest version at thinkpython.com; I am revising now,
0
1125
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, and there is no other possibility) then __cmp__ is enough, and easier to define than all the rich comparison operations. In other cases, __cmp__ is not suitable: by example, complex numbers can't define "greater than" ; you can only use "equal" or...
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10215
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10049
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9996
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6674
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5307
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3964
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3564
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.