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? 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
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
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
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
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
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
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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...
|
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...
|
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:
...
|
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...
|
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...
|
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...
|
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...
|
by: Konstantinos Pachopoulos |
last post by:
Hi,
i have the following class:
===========================================
class CmterIDCmts:
def __init__(self,commiterID,commits):
self.commiterID_=long(commiterID)...
|
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...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
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$) {
}
...
|
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...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
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...
|
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...
|
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,...
|
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...
|
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...
| |