473,545 Members | 2,001 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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*******@gmai l.com>
>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:
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
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
(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 NotImplementedE rror

Now you can override _len_impl in the instance:

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

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

Gabriel Genellina

Oct 23 '08 #1
0 1099

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

Similar topics

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 arguments, got 0". Tested with Python 2.3.4 on OpenBSD and Python 2.4 on Win98; same results. Is this a bug in deepcopy, how I dynamically assign the...
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)> myFunctor = SampleFunction; string result = myFunctor(7, true); Works great thanks to the help from this group. Here's the guts so far for two-arity:
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 you use the :: scoping operator to directly call the base class method. Like this: class BASE
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; dll=Assembly.LoadFrom(@"c:\app\Assembly.dll");
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); }
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
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 = NewClass() newobj.__dict__.update(object.__dict__) return newobj
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 instance method? (there is a class method with the same name) 2) how do I dynamically delete the instance method?
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 signature of method to pass a new parameter, I am setting the custom attribute of a given method and then accessing the attribute from method. Since...
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 looks like maybe not. Here is the test case I tried: class A(object):
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...
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. ...
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...
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...
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...
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...
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...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
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

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.