473,686 Members | 3,494 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

substitution __str__ method of an instance

I couldn't substitute __str__ method of an instance. Though I managed
to substitute ordinary method of an instance:

from types import MethodType

class Foo(object):
pass

class Printer(object) :

def __call__(self, obj_self):
return 'printed'

f = Foo()

f.printer = MethodType(Prin ter(), f, Foo)
print f.printer() # works fine - I get: 'printed'

print f # get: <__main__.Foo object at 0x00D69C10>
f.__str__ = MethodType(Prin ter(), f, Foo)
print f # still get: <__main__.Foo object at 0x00D69C10>. Why?
Foo.__str__ = MethodType(Prin ter(), None, Foo)
print f # works fine - I get: 'printed'
How can I substitute __str__ method of an instance?
Oct 23 '08 #1
7 1415
netimen wrote:
I couldn't substitute __str__ method of an instance. Though I managed
to substitute ordinary method of an instance:

from types import MethodType

class Foo(object):
pass

class Printer(object) :

def __call__(self, obj_self):
return 'printed'

f = Foo()

f.printer = MethodType(Prin ter(), f, Foo)
print f.printer() # works fine - I get: 'printed'

print f # get: <__main__.Foo object at 0x00D69C10>
f.__str__ = MethodType(Prin ter(), f, Foo)
print f # still get: <__main__.Foo object at 0x00D69C10>. Why?
Foo.__str__ = MethodType(Prin ter(), None, Foo)
print f # works fine - I get: 'printed'
How can I substitute __str__ method of an instance?
You can't. Special methods are only looked up on classes.

Diez
Oct 23 '08 #2
netimen wrote:
How can I substitute __str__ method of an instance?
It's not possible. For performance and other reasons most __*__ methods
are looked up on the type only.

Christian

Oct 23 '08 #3
Christian Heimes wrote:
netimen wrote:
>How can I substitute __str__ method of an instance?

It's not possible. For performance and other reasons most __*__ methods
are looked up on the type only.
Is that documented somewhere? I *know* it is that way, yet I'd like to have
place to read up on it (and point to when this question pops up)

Diez
Oct 23 '08 #4
netimen a écrit :
I couldn't substitute __str__ method of an instance. Though I managed
to substitute ordinary method of an instance:

from types import MethodType

class Foo(object):
pass

class Printer(object) :

def __call__(self, obj_self):
return 'printed'

f = Foo()

f.printer = MethodType(Prin ter(), f, Foo)
print f.printer() # works fine - I get: 'printed'

print f # get: <__main__.Foo object at 0x00D69C10>
f.__str__ = MethodType(Prin ter(), f, Foo)
print f # still get: <__main__.Foo object at 0x00D69C10>. Why?
Foo.__str__ = MethodType(Prin ter(), None, Foo)
print f # works fine - I get: 'printed'
How can I substitute __str__ method of an instance?
Now that others told you you couldn't do so, there's eventually a
workaround - that is, if you have the hand on class Foo:

class Foo(object):
def __str__(self):
printer = getattr(self, 'printer', super(Foo, self).__str__)
return printer()

HTH
Oct 23 '08 #5
Diez B. Roggisch a écrit :
Christian Heimes wrote:
>netimen wrote:
>>How can I substitute __str__ method of an instance?
It's not possible. For performance and other reasons most __*__ methods
are looked up on the type only.

Is that documented somewhere? I *know* it is that way, yet I'd like to have
place to read up on it (and point to when this question pops up)
http://docs.python.org/reference/dat...-style-classes

Oct 23 '08 #6
On Thu, 23 Oct 2008 10:55:56 +0200, Christian Heimes wrote:
netimen wrote:
>How can I substitute __str__ method of an instance?

It's not possible. For performance and other reasons most __*__ methods
are looked up on the type only.

Christian
However, you can dispatch back to the instance if you really must:
class MyObj(object):
def __init__(self):
self.__str__ = lambda self: "I'm an object!"
def __str__(self):
return self.__str__(se lf)
But honestly, this sounds like a bad idea. If instances of the one class
have such radically different methods that they need to be treated like
this, I question whether they actually belong in the same class.


--
Steven
Oct 23 '08 #7
Steven D'Aprano <st***@REMOVE-THIS-cybersource.com .auwrote:
However, you can dispatch back to the instance if you really must:
class MyObj(object):
def __init__(self):
self.__str__ = lambda self: "I'm an object!"
def __str__(self):
return self.__str__(se lf)
But honestly, this sounds like a bad idea. If instances of the one
class
have such radically different methods that they need to be treated
like
this, I question whether they actually belong in the same class.
Another option would be to just change the class of the object:
>>class C(object):
pass
>>c = C()
print c
<__main__.C object at 0x01180C70>
>>def wrapstr(instanc e, fn=None):
if fn is None:
def fn(self): return "I'm an object"
Wrapper = type(instance._ _class__.__name __, (instance.__cla ss__,),
{'__str__':fn})
instance.__clas s__ = Wrapper

>>wrapstr(c)
print c
I'm an object
>>isinstance( c, C)
True
>>type(c)
<class '__main__.C'>
>>wrapstr(c, lambda s: "object %s at %s" % (type(s).__name __, id(s)))
print c
object C at 18353264

(I'll leave enhancing wrapstr so that it avoids multiple levels of
wrapping as an exercise for anyone who actually wants to use it.)

--
Duncan Booth http://kupuguy.blogspot.com
Oct 24 '08 #8

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

Similar topics

15
5946
by: Jim Newton | last post by:
hi all, does anyone know what print does if there is no __str__ method? i'm trying ot override the __repr__. If anyone can give me some advice it would be great to have. I have defined a lisp-like linked list class as a subclass of list. The __iter__ seems to work as i'd like, by traversing the links, and the __repr__ seems to work properly for somethings but not others. The basic idea is that a list such as is converted to ]],...
3
1819
by: Dan Sommers | last post by:
Hi, I have a class whose objects represent physical quantities including uncertainties and units, and I would like more control over the way they print. I have a __str__ method which outputs the quantity and its uncertainty, properly rounded (i.e. the uncertainty to one digit and the quantity to the same precision as the uncertainty), followed by the units (mostly) as they accumulated during whatever calculations led to the quantity's
15
2927
by: Jan Danielsson | last post by:
Sorry, but I Just Don't Get It. I did search the 'net, I did read the FAQ, but I'm too dumb to understand. As far as I can gather, __str__ is just a representation of the object. For instance: class ServerConnection: def __str__(self): buf = "Server: " + self.name + "\n" buf += "Sent bytes: " + str(self.sentBytes) + "\n"
7
1909
by: Jeffrey E. Forcier | last post by:
I am attempting to write a class whose string representation changes in response to external stimuli. While that effect is obviously possible via other means, I attempted this method first and was surprised when it didn't work, so I now want to know why :) Given the following class definition: class MyClass(object): def Edit(self):
1
2377
by: kollareddy | last post by:
Hi all, I am new to xml/xsd world. I want to know the differences between complex type and element being abstract and if both can be declared so, in case of substitution goups.Also can xsi:type usuage allowes in instance doucments in case of substitution goups. I tried using abstarct complex type/element with substitution groups and I attached the code below. In XX1.xsd which is imported and a reference to complex abstract type is made...
1
1247
by: Ilias Lazaridis | last post by:
I have some python code which looks similar to this: class Car(BaseClass) : manufacturer = factory.string() model = factory.string() modelYear = factory.integer() def __str__(self): return '%s %s %s' % (self.modelYear, self.manufacturer, self.model)
5
2465
by: Mike Krell | last post by:
I'm running into problems trying to override __str__ on the path class from Jason Orendorff's path module (http://www.jorendorff.com/articles/python/path/src/path.py). My first attempt to do this was as follows: ''' class NormPath(path): def __str__(self): return 'overridden __str__: ' + path.__str__(self.normpath())
5
5047
by: Konstantinos Pachopoulos | last post by:
Hi, i have the following class: =========================================== class CmterIDCmts: def __init__(self,commiterID,commits): self.commiterID_=long(commiterID) self.commits_=long(commits) def __str__(self):
6
1504
by: netimen | last post by:
Can I substitute a method of a class by a callable object (not a function)? I can very easy insert my function in a class as a method, but an object - can't. I have the following: class Foo(object): pass class Obj(object):
0
8514
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
8932
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...
0
8778
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7598
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6439
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
5795
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
4307
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...
1
2944
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
1933
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.