473,769 Members | 4,052 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Type emulation issues with new style classes

Is there any way to make the class Z behave the same way as class Y?

Chris

class Y:
value = 42
def __hasattr__(sel f, name):
if name == '__int__':
return True
def __getattr__(sel f, name):
if name == '__int__':
return lambda: self.value

class Z(object):
value = 42
def __hasattr__(sel f, name):
if name == '__int__':
return True
def __getattr__(sel f, name):
if name == '__int__':
return lambda: self.value
y, z = Y(), Z()
print int(y) 42 print int(z)

TypeError: int() argument must be a string or a number
Jul 18 '05 #1
16 1678
class Z(object):
value = 42
def __hasattr__(sel f, name):
if name == '__int__':
return True
def __int__(self):
return self.value

Umm, maybe I haven't understood what you need.

--
Don't you know why your Python application has crashed?
Take a look to http://www.pycrash.org
--
Posted via Mailgate.ORG Server - http://www.Mailgate.ORG
Jul 18 '05 #2
I need to have Python call the the emulation methods for numbers, lists,
etc, when those methods are provided though __getattr__ rather than defined
in the instance or class __dict__. I've been up and down PEP 252 trying to
determine how Python determines the presence or absence of emulation methods
for new style classes, but I'm not having any luck.

"Carmine Noviello" wrote:
class Z(object):
value = 42
def __hasattr__(sel f, name):
if name == '__int__':
return True
def __int__(self):
return self.value
Umm, maybe I haven't understood what you need.


I need to know how I can do what I previously demonstrated with an old style
class, that is hook into Python's introspection mechanism to dynamically
provide an __int__ method (or optionally __str__, __lt__, __le__, __eq__
,__ne__, __gt__, __ge__, __len__, __getitem__, __add__, __sub__, __mul__,
__floordiv__, __mod__, __divmod__, __pow__, __lshift__, ... ad nausuem).
Old style classes will let me do this, but I cannot determine how to do this
with new style classes.

Chris
Jul 18 '05 #3
In article <C0************ ****@nwrdny03.g nilink.net>,
Chris <fe************ *@spamgourmet.c om> wrote:

class Z(object):
value = 42
def __hasattr__(sel f, name):
if name == '__int__':
return True
def __getattr__(sel f, name):
if name == '__int__':
return lambda: self.value


IIRC, __getattribute_ _ may do what you want, but I don't have time to
check.
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

"Do not taunt happy fun for loops. Do not change lists you are looping over."
--Remco Gerlich, comp.lang.pytho n
Jul 18 '05 #4
Tried it earlier, same result.

Chris

"Aahz" wrote:
IIRC, __getattribute_ _ may do what you want, but I don't have time to
check.
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/
"Do not taunt happy fun for loops. Do not change lists you are looping over." --Remco Gerlich, comp.lang.pytho n

Jul 18 '05 #5
"Chris" <fe************ *@spamgourmet.c om> writes:
Is there any way to make the class Z behave the same way as class Y?


You need a custom metaclass for Z, and implement __getattr__ there.

HTH.

Cheers,
mwh

--
Lisp does badly because we refuse to lie. When people ask us if
we can solve insoluble problems we say that we can't, and because
they expect us to lie to them, they find some other language
where the truth is less respected. -- Tim Bradshaw, comp.lang.lisp
Jul 18 '05 #6
I tried a couple variation of that, and __getattr__, when defined in a
metaclass is never called when accessing an attribute on an instance of a
class derived from that metaclass.

Here is some testing I did:

class Zmeta(type):
def __getattribute_ _(*args):
raise Exception('call ed __getattribute_ _ with %s' % str(args))
def __getattr__(*ar gs):
raise Exception('call ed __getattr__ with %s' % str(args))

Z = Zmeta('Z', (), {'value': 42})
z = Z()
int(z) TypeError: int() argument must be a string or a number z.__int__ AttributeError: 'Z' object has no attribute '__int__' Z.__int__
Exception: called __getattribute_ _ with (<class '__main__.Z'>, '__int__')

It appears (and is confirmed in: Metaclass Programming in Python Pt. 2
http://www-106.ibm.com/developerwork...a2/?ca=dnt-434) that
metaclass attributes are available to instances (classes) but not instances
of instances.

Chris

"Michael Hudson" wrote:
Is there any way to make the class Z behave the same way as class Y?


You need a custom metaclass for Z, and implement __getattr__ there.

HTH.

Cheers,
mwh

--
Lisp does badly because we refuse to lie. When people ask us if
we can solve insoluble problems we say that we can't, and because
they expect us to lie to them, they find some other language
where the truth is less respected. -- Tim Bradshaw, comp.lang.lisp

Jul 18 '05 #7
Chris wrote:
class Z(object):
value = 42
def __hasattr__(sel f, name):
if name == '__int__':
return True
def __getattr__(sel f, name):
if name == '__int__':
return lambda: self.value

def __int__(self):
return self.__getattr_ _('__int__')()
--
Rainer Deyke - ra*****@eldwood .com - http://eldwood.com
Jul 18 '05 #8
On Sat, 28 Feb 2004 11:33:54 GMT, "Chris" <fe************ *@spamgourmet.c om>
wrote:
class Z(object):
value = 42
def __hasattr__(sel f, name):
if name == '__int__':
return True
def __getattr__(sel f, name):
if name == '__int__':
return lambda: self.value


The following allows your test case to work, but it may have various subtle
problems. AddDynOper emulates __getattr__ semantics: the descriptor is not
installed if the type already has an attribute of the given name:

class DynOperDescr(ob ject):
def __init__(self, name):
self.name = name
def __get__(self, instance, typ):
if instance is None:
return self
return instance.__geta ttr__(self.name )

def AddDynOper(decl cls, name):
if not hasattr(declcls , name):
setattr(declcls , name, DynOperDescr(na me))

class Z(object):
value = 42
def __getattr__(sel f, name):
if name == "__int__":
return lambda : self.value
raise AttributeError( name)
AddDynOper(Z, "__int__")

---
Greg Chapman

Jul 18 '05 #9
I'm looking for a way to do this without explicity definining every
emulation method, i.e. (__str__, __lt__, __le__, __eq__, __ne__, __gt__,
__ge__, __len__, __getitem__, __add__, __sub__, __mul__, __floordiv__,
__mod__, __divmod__, __pow__, __lshift__, ... ad nausuem). Plus, there's a
few this isn't going to work for several of the the arithmetic operators,
such as when I want to have __add__ undefined so Python will attpemt
__radd__. For example:

class Y:
value = 42
def __getattr__(sel f, name):
if name == '__coerce__':
raise AttributeError
if name == '__add__':
raise AttributeError
if name == '__radd__':
return lambda other: self.value + other.value
y1, y2 = Y(), Y()
print int(y1) #This works 42 print y1 + y2 #This works too 84

class Z(object):
value = 42
def __getattr__(sel f, name):
if name == '__add__':
raise AttributeError
if name == '__radd__':
return lambda other: Z.value + Z.value
if name == '__int__':
return lambda: self.value
def __int__(self):
return self.__getattr_ _('__int__')()
def __add__(self, other):
return self.__getattr_ _('__add__')()
def __radd__(self, other):
return self.__getattr_ _('__radd__')()

z1, z2 = Z(), Z()
# This following will work now, after explicitly
# adding __int__ to the namespace of Z, which I'm
# trying to avoid.
print int(z1) 42 print y1 + y2 # This bombs
TypeError: 'NoneType' object is not callable

"Rainer Deyke" wrote: Chris wrote:
class Z(object):
value = 42
def __hasattr__(sel f, name):
if name == '__int__':
return True
def __getattr__(sel f, name):
if name == '__int__':
return lambda: self.value

def __int__(self):
return self.__getattr_ _('__int__')()
--
Rainer Deyke - ra*****@eldwood .com - http://eldwood.com

Jul 18 '05 #10

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

Similar topics

1
1337
by: Michal Vitecek | last post by:
hello, does the type() command work correctly for new style classes? i guess it does not, unfortunately. for example, for a new style class' instance it returns <class '__main__.ClassName'>, but for old style class' instance it returns <type 'instance'>. >>> import types >>> class A(object): pass
5
1395
by: Batista, Facundo | last post by:
I'm proud to announce that the PEP for Decimal Data Type is now published under the python.org structure: http://www.python.org/peps/pep-0327.html This wouldn't has been possible without the help from Alex Martelli, Aahz, Tim Peters, David Goodger and c.l.p itself. After the pre-PEP roundups the features are almost established. There is not agreement yet on how to create a Decimal from a float, in both explicit and
3
4348
by: ShadowMan | last post by:
Hi all I've seen a lot of posts about frames emulation. I would like to emulate a: header, left-side menu, content, footer layout. I need to be cross browser compatible...but I'm get crazy!!! My code is above: it displays right on Firefox 1.0 but it doesn't on IE6. What should I change?! thanx --
3
1338
by: Serge Skorokhodov (216716244) | last post by:
Hi, I just seeking advice. Some background information first because I've run into issues that seems pretty obscure to me:( Quick search through KB yields next to nothing. Simplified samples work OK as well, the problems appear in rather bulky code:( I'm trying to implement some signal processing algorithm using
4
3083
by: Kevin Newman | last post by:
The primary problem I've had with php is the lack of namespaces, which makes OOP very difficult to organize, since you end up with large number of classes cluttering up the same namespace - which leads to a secondary problem involving php's __autoload feature. Since you cannot specify a namespace when calling a class that may not have been included, you are forced to store all of your classes in the same folder in your file system. This...
28
1953
by: VK | last post by:
A while ago I wrote a "Vector data type" script using DOM interface to select.options. That was a (beautiful) mind game :-) rather than a practical thing to use. Here is another attempt open for criticism, this time dead serious. I really need an effective Vector emulator for a project (as much effective as something not implemeted in language but emulated by means of the language itself is: a
5
3173
by: JH | last post by:
Hi I found that a type/class are both a subclass and a instance of base type "object". It conflicts to my understanding that: 1.) a type/class object is created from class statement 2.) a instance is created by "calling" a class object.
8
1711
by: =?Utf-8?B?ZG1idXNv?= | last post by:
I'm migrating a VB.NET 2003 application to VB.NET 2008. The 2003 app used the June 2005 Enterprise Library while I'm going to use the latest EntLib, 4.0 - May 2008. I copied the 2003 app to a new 2008 folder structure, recreated the app.config using the new 4.0 EntLib config tool, and referenced the 4.0 Microsoft.Practices.EnterpriseLibrary.Data.dll file. The problem is there is a Function that has errors in it and I'm not sure how to...
21
5202
by: Nikolaus Rath | last post by:
Hello, Can someone explain to me the difference between a type and a class? After reading http://www.cafepy.com/article/python_types_and_objects/ it seems to me that classes and types are actually the same thing: - both are instances of a metaclass, and the same metaclass ('type') can instantiate both classes and types. - both can be instantiated and yield an "ordinary" object - I can even inherit from a type and get a class
0
9423
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
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,...
1
7410
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
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
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
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.