473,320 Members | 1,802 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,320 software developers and data experts.

Re: add method to class dynamically?

En Wed, 22 Oct 2008 10:37:11 -0200, Jean-Paul Calderone
<ex*****@divmod.comescribió:
On Wed, 22 Oct 2008 08:29:08 -0400, Neal Becker <nd*******@gmail.com>
wrote:
>I have a class (actually implemented in c++ using boost::python). For
an instance of this class, 'r', I'd like to support len (r). I don't
want to add it to the c++ code, because this is a unique situation:
this class should not normally support len().

So I try:
r = ring_int (10)
r.__len__ = lambda: 10

This doesn't work:
>>>>len(r)
TypeError: object of type 'ring_int' has no len()
Special methods aren't looked up in the instance dict of instances of
new-style classes. Exactly what constitutes the set of "special methods"
is a bit undefined. Consider anything that CPython has to look up to
satisfy some other operation, such as len or +, to be a special method
and don't rely on _either_ it being looked up on the instance or it _not_
being looked up on the instance (ie, don't put a method there and expect
it
not to be called). The methods which are actually considered special by
CPython can change and has in the past.
All special methods have names like "__special__" (except "next" -used in
the iterator protocol- which will become __next__ in 3.0; any others?) -
this is stated here
http://docs.python.org/reference/lex...of-identifiers.
(But I'm sure you already knew that)

To the OP: you may use a "template method". In the C++ class do the
equivalent of:

class Ring_int(int):
def __len__(self): return self._len_impl()
def _len_impl(self): raise NotImplementedError

Now you can override _len_impl in the instance:

pyr = Ring_int(10)
pyr._len_impl = lambda: 10
pylen(r)
10

Note that hasattr(r, '__len__') is true, don't use that check in this case.

--
Gabriel Genellina

Oct 23 '08 #1
0 1090

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

Similar topics

7
by: ‘5ÛHH575-UAZWKVVP-7H2H48V3 | last post by:
(see end of message for example code) When an instance has a dynamically assigned instance method, deepcopy throws a TypeError with the message "TypeError: instancemethod expected at least 2...
4
by: daniel.w.gelder | last post by:
I wrote a template class that takes a function prototype and lets you store and call a C-level function, like this: inline string SampleFunction(int, bool) {..} functor<string (int, bool)>...
4
by: Amy Matlock | last post by:
Hi all: How does the hardware work if you invoke a BASE::METHOD() on a DERIVED class member? Do you still hit the v-table dynamically at run time? Suppose you have a derived class method, but...
9
by: keith | last post by:
I created a class libery which has name space Assembly and class Assembly and compiled it. Then created a C# project and called a method in the external class e.g. Assembly dll;...
5
by: Rik Hemsley | last post by:
How does one go about getting a pointer to method as an IntPtr? Example: public class A { public void X() { Y(Z); }
44
by: gregory.petrosyan | last post by:
Hello everybody! I have little problem: class A: def __init__(self, n): self.data = n def f(self, x = ????) print x All I want is to make self.data the default argument for self.f(). (I
23
by: digitalorganics | last post by:
How can an object replace itself using its own method? See the following code: class Mixin: def mixin(object, *classes): NewClass = type('Mixin', (object.__class__,) + classes, {}) newobj =...
2
by: Danny | last post by:
howdy, I have created an instance method for an object using new.instancemethod. It works great. Now the questions are: 1) how do I dynamically inspect an object to determine if it has an...
4
by: =?Utf-8?B?QWJoaQ==?= | last post by:
I am using Reflection to invoke methods dynamically. I have got a special requirement where I need to pass a value to method by setting the custom method attribute. As I cannot change the...
3
by: allendowney | last post by:
Hi All. In a complex inheritance hierarchy, it is sometimes difficult to find where a method is defined. I thought it might be possible to get this info from the method object itself, but it...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.