473,387 Members | 2,436 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,387 software developers and data experts.

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(Printer(), f, Foo)
print f.printer() # works fine - I get: 'printed'

print f # get: <__main__.Foo object at 0x00D69C10>
f.__str__ = MethodType(Printer(), f, Foo)
print f # still get: <__main__.Foo object at 0x00D69C10>. Why?
Foo.__str__ = MethodType(Printer(), None, Foo)
print f # works fine - I get: 'printed'
How can I substitute __str__ method of an instance?
Oct 23 '08 #1
7 1404
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(Printer(), f, Foo)
print f.printer() # works fine - I get: 'printed'

print f # get: <__main__.Foo object at 0x00D69C10>
f.__str__ = MethodType(Printer(), f, Foo)
print f # still get: <__main__.Foo object at 0x00D69C10>. Why?
Foo.__str__ = MethodType(Printer(), 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(Printer(), f, Foo)
print f.printer() # works fine - I get: 'printed'

print f # get: <__main__.Foo object at 0x00D69C10>
f.__str__ = MethodType(Printer(), f, Foo)
print f # still get: <__main__.Foo object at 0x00D69C10>. Why?
Foo.__str__ = MethodType(Printer(), 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__(self)
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__(self)
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(instance, fn=None):
if fn is None:
def fn(self): return "I'm an object"
Wrapper = type(instance.__class__.__name__, (instance.__class__,),
{'__str__':fn})
instance.__class__ = 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
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...
3
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...
15
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: ...
7
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...
1
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...
1
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...
5
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...
5
by: Konstantinos Pachopoulos | last post by:
Hi, i have the following class: =========================================== class CmterIDCmts: def __init__(self,commiterID,commits): self.commiterID_=long(commiterID)...
6
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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,...
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
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...

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.