I've got an instance of a class, ex :
b=gtk.Button()
I'd like to add methods and attributes to my instance "b".
I know it's possible by hacking "b" with setattr() methods. But i'd
like to do it with inheritance, a kind of "dynamic subclassing",
without subclassing the class, only this instance "b" !
In fact, i've got my instance "b", and another class "MoreMethod s"
class MoreMethods:
def sayHello(self):
print "hello"
How could i write ...
"b = b + MoreMethods"
so "b" will continue to be a gtk.Button, + methods/attributs of
MoreMethods (it's what i call "dynamic inheritance") ...so, things
like this should work :
- b.set_label("k" )
- b.sayHello()
I can't find the trick, but i'm pretty sure it's possible in an easy
way.
Help is welcome
thanx 16 2040
manatlan a écrit :
I've got an instance of a class, ex :
b=gtk.Button()
I'd like to add methods and attributes to my instance "b".
I know it's possible by hacking "b" with setattr() methods.
You don't even need setattr() here, you can set the attributes directly.
But i'd
like to do it with inheritance, a kind of "dynamic subclassing",
without subclassing the class, only this instance "b" !
In fact, i've got my instance "b", and another class "MoreMethod s"
class MoreMethods:
def sayHello(self):
print "hello"
How could i write ...
"b = b + MoreMethods"
so "b" will continue to be a gtk.Button, + methods/attributs of
MoreMethods (it's what i call "dynamic inheritance") ...so, things
like this should work :
- b.set_label("k" )
- b.sayHello()
I can't find the trick, but i'm pretty sure it's possible in an easy
way.
You don't necessarily need subclassing here. What you want is a typical
use case of the Decorator pattern:
class MoreMethods(obj ect):
def __init__(self, button):
self._button = button
def sayHello(self):
print "hello"
def __getattr__(sel f, name):
return getattr(self._b utton, name)
def __setattr__(sel f, name, value):
if name in dir(self._butto n):
setattr(self._b utton, name, value)
else:
object.__setatt r__(self, name, value)
b = MoreMethods(gtk .Button())
b.set_label("k" )
b.say_hello()
On 12 mai, 17:00, Bruno Desthuilliers
<bdesth.quelque ch...@free.quel quepart.frwrote :
manatlan a écrit :
I've got an instance of a class, ex :
b=gtk.Button()
I'd like to add methods and attributes to my instance "b".
I know it's possible by hacking "b" with setattr() methods.
You don't even need setattr() here, you can set the attributes directly.
But i'd
like to do it with inheritance, a kind of "dynamic subclassing",
without subclassing the class, only this instance "b" !
In fact, i've got my instance "b", and another class "MoreMethod s"
class MoreMethods:
def sayHello(self):
print "hello"
You don't necessarily need subclassing here. What you want is a typical
use case of the Decorator pattern:
class MoreMethods(obj ect):
def __init__(self, button):
self._button = button
def sayHello(self):
print "hello"
def __getattr__(sel f, name):
return getattr(self._b utton, name)
def __setattr__(sel f, name, value):
if name in dir(self._butto n):
setattr(self._b utton, name, value)
else:
object.__setatt r__(self, name, value)
b = MoreMethods(gtk .Button())
b.set_label("k" )
b.say_hello()
except that "b" is not anymore a "gtk.Button ", but a "MoreMethod s"
instance ...
i'd like that "b" stay a "gtk.Button " ...
I've got an instance of a class, ex :
>
b=gtk.Button()
I'd like to add methods and attributes to my instance "b".
I know it's possible by hacking "b" with setattr() methods. But i'd
like to do it with inheritance, a kind of "dynamic subclassing",
without subclassing the class, only this instance "b" !
In fact, i've got my instance "b", and another class "MoreMethod s"
class MoreMethods:
def sayHello(self):
print "hello"
How could i write ...
"b = b + MoreMethods"
so "b" will continue to be a gtk.Button, + methods/attributs of
MoreMethods (it's what i call "dynamic inheritance") ...so, things
like this should work :
- b.set_label("k" )
- b.sayHello()
I can't find the trick, but i'm pretty sure it's possible in an easy
way.
How about :
class MoreMethods:
def sayHello(self):
print "hello"
class myButton( gtk.Button, MoreMethods ):
pass
b = myButton( )
isinstance( b, gtk.Button ) # True
b.sayHello( ) # "hello"
Daniel
On 12 mai, 18:38, "Daniel Nogradi" <nogr...@gmail. comwrote:
I've got an instance of a class, ex :
b=gtk.Button()
I'd like to add methods and attributes to my instance "b".
I know it's possible by hacking "b" with setattr() methods. But i'd
like to do it with inheritance, a kind of "dynamic subclassing",
without subclassing the class, only this instance "b" !
In fact, i've got my instance "b", and another class "MoreMethod s"
class MoreMethods:
def sayHello(self):
print "hello"
How could i write ...
"b = b + MoreMethods"
so "b" will continue to be a gtk.Button, + methods/attributs of
MoreMethods (it's what i call "dynamic inheritance") ...so, things
like this should work :
- b.set_label("k" )
- b.sayHello()
I can't find the trick, but i'm pretty sure it's possible in an easy
way.
How about:
class MoreMethods:
def sayHello(self):
print "hello"
class myButton( gtk.Button, MoreMethods ):
pass
b = myButton( )
isinstance( b, gtk.Button ) # True
b.sayHello( ) # "hello"
yes, but it needs to recreate an instance (of mybutton) ...
i can't do that, in my context.
The only things i've got is my instance "b" (which can be whatever
object).
i'd like to add methods/attributes to this instance, by adding a
heritage of another class.
Daniel
thanks
manatlan wrote:
I can't find the trick, but i'm pretty sure it's possible in an easy
way.
It's somewhat easy, boot looks ugly to me. Maybe someone has a more
elegant solution:
In [6]: import new
In [13]: class Button:
....: def buttonFunc(self ):
....: pass
In [14]: class ExtensionClass:
....: def extendedMethod( self):
....: pass
In [15]: hybrid = new.instance(Bu tton,
Button.__dict__ .update(Extensi onClass.__dict_ _))
In [17]: dir(hybrid)
Out[17]: ['__doc__', '__module__', 'buttonFunc', 'extendedMethod ']
Seems to do what you want it to do.
HTH,
Karlo.
I've got an instance of a class, ex :
b=gtk.Button()
I'd like to add methods and attributes to my instance "b".
I know it's possible by hacking "b" with setattr() methods. But i'd
like to do it with inheritance, a kind of "dynamic subclassing",
without subclassing the class, only this instance "b" !
In fact, i've got my instance "b", and another class "MoreMethod s"
class MoreMethods:
def sayHello(self):
print "hello"
How could i write ...
"b = b + MoreMethods"
so "b" will continue to be a gtk.Button, + methods/attributs of
MoreMethods (it's what i call "dynamic inheritance") ...so, things
like this should work :
- b.set_label("k" )
- b.sayHello()
I can't find the trick, but i'm pretty sure it's possible in an easy
way.
How about:
class MoreMethods:
def sayHello(self):
print "hello"
class myButton( gtk.Button, MoreMethods ):
pass
b = myButton( )
isinstance( b, gtk.Button ) # True
b.sayHello( ) # "hello"
yes, but it needs to recreate an instance (of mybutton) ...
i can't do that, in my context.
The only things i've got is my instance "b" (which can be whatever
object).
i'd like to add methods/attributes to this instance, by adding a
heritage of another class.
I think that is not possible, at least in a simple way (there might be
a complicated way of messing with the MRO). Please anyone correct me
if I was wrong.
Daniel
manatlan wrote:
I've got an instance of a class, ex :
b=gtk.Button()
I'd like to add methods and attributes to my instance "b".
I know it's possible by hacking "b" with setattr() methods. But i'd
like to do it with inheritance, a kind of "dynamic subclassing",
without subclassing the class, only this instance "b" !
In fact, i've got my instance "b", and another class "MoreMethod s"
class MoreMethods:
def sayHello(self):
print "hello"
How could i write ...
"b = b + MoreMethods"
You can simply bind the methods you want to add to the Button instance.
That means doing the equivalent of ``b.sayHello = sayHello.__get_ _(b)``.
For example::
>>class Button(object):
... def set_label(self, label):
... print 'setting label:', label
...
>>def add_methods(obj , cls):
... for name, value in cls.__dict__.it ems():
... if callable(value) and hasattr(value, '__get__'):
... setattr(obj, name, value.__get__(o bj, type(obj)))
...
>>b = Button() b.set_label(' k')
setting label: k
>>b.say_hello ()
Traceback (most recent call last):
File "<interacti ve input>", line 1, in <module>
AttributeError: 'Button' object has no attribute 'say_hello'
>>class MoreMethods(obj ect):
... def say_hello(self) :
... print 'hello'
...
>>add_methods(b , MoreMethods) b.set_label(' m')
setting label: m
>>b.say_hello ()
hello
HTH,
STeVe
manatlan <ma******@gmail .comwrote:
I've got an instance of a class, ex :
b=gtk.Button()
I'd like to add methods and attributes to my instance "b".
I know it's possible by hacking "b" with setattr() methods. But i'd
like to do it with inheritance, a kind of "dynamic subclassing",
without subclassing the class, only this instance "b" !
In fact, i've got my instance "b", and another class "MoreMethod s"
class MoreMethods:
def sayHello(self):
print "hello"
How could i write ...
"b = b + MoreMethods"
so "b" will continue to be a gtk.Button, + methods/attributs of
MoreMethods (it's what i call "dynamic inheritance") ...so, things
like this should work :
- b.set_label("k" )
- b.sayHello()
I can't find the trick, but i'm pretty sure it's possible in an easy
way.
I think what you're asking for is totally weird, and with just about
zero advantages compared with several saner alternatives that have
already been proposed in this thread and that you have rejects, but
sure, it's possible:
def addaclass(anins t, onemoreclass):
aninst.__class_ _ = type(aninst.__a class__.__name_ _,
(aninst.__aclas s__, onemoreclass), {})
Alex
On 13 mai, 01:24, a...@mac.com (Alex Martelli) wrote:
manatlan <manat...@gmail .comwrote:
I've got an instance of a class, ex :
b=gtk.Button()
I'd like to add methods and attributes to my instance "b".
I know it's possible by hacking "b" with setattr() methods. But i'd
like to do it with inheritance, a kind of "dynamic subclassing",
without subclassing the class, only this instance "b" !
In fact, i've got my instance "b", and another class "MoreMethod s"
class MoreMethods:
def sayHello(self):
print "hello"
How could i write ...
"b = b + MoreMethods"
so "b" will continue to be a gtk.Button, + methods/attributs of
MoreMethods (it's what i call "dynamic inheritance") ...so, things
like this should work :
- b.set_label("k" )
- b.sayHello()
I can't find the trick, but i'm pretty sure it's possible in an easy
way.
I think what you're asking for is totally weird, and with just about
zero advantages compared with several saner alternatives that have
already been proposed in this thread and that you have rejects, but
sure, it's possible:
def addaclass(anins t, onemoreclass):
aninst.__class_ _ = type(aninst.__a class__.__name_ _,
(aninst.__aclas s__, onemoreclass), {})
Alex
I know it's weird ... and solutions given here are a lot saner. But i
can't do that at the creation of the instance, because it's not me who
has the creation process ... the only things i've got, it's the
instance
i tried :
class MoreMethods:
def sayHello(self):
print "hello"
def addaclass(anins t, onemoreclass):
aninst.__class_ _ = type(aninst.__c lass__.__name__ ,
(aninst.__class __, onemoreclass), {})
b=gtk.Button("t he_label")
addaclass(b,Mor eMethods)
print b.get_label()
print b.hello()
but got :
"TypeError: __class__ assignment: only for heap types"
on the last line ...
I begin to think that the only solution is to use the module new like
Karlo said ... This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: WhiteRavenEye |
last post by:
Why can't I subclass any window except mine in VB?
Do I have to write dll for this?
I've tried to subclass it with SetWindowLong but without success...
Does anyone know how to subclass window ANY window in VB?
Thanks...
|
by: GrelEns |
last post by:
hello,
i wonder if this possible to subclass a list or a tuple and add more
attributes ? also does someone have a link to how well define is own
iterable object ?
what i was expecting was something like :
>>> t = Test('anAttributeValue', )
>>> t.anAttribute
|
by: David Vaughan |
last post by:
I'm using v2.3, and trying to write to text files, but with a maximum
line length. So, if a line is getting too long, a suitable ' '
character is replaced by a new line. I'm subclassing the file class,
and, as long as I just use the write method, this works fine. But
"print >>" doesn't behave as I want:
class max_width_file(file):
def...
|
by: BJörn Lindqvist |
last post by:
A problem I have occured recently is that I want to subclass builtin
types. Especially subclassing list is very troublesome to me. But I
can't find the right syntax to use. Take for example this class which
is supposed to be a representation of a genome:
class Genome(list):
def __init__(self):
list.__init__(self)
self =
....
|
by: Peter Olsen |
last post by:
I want to define a class "point" as a subclass of complex.
When I create an instance
sample = point(<arglist>)
I want "sample" to "be" a complex number, but with its real and
imaginary parts computed in point()'s __init__ function with their
values based on the arglist. I want to compute with point instances
as though they were native...
| |
by: Brent |
last post by:
I'd like to subclass the built-in str type. For example:
--
class MyString(str):
def __init__(self, txt, data):
super(MyString,self).__init__(txt)
self.data = data
|
by: Marvin |
last post by:
Hi,
It's been claimed that inheritance structures are less important in dynamic
languages like Python. Why is that and where can i read more about that?
/Marv
|
by: devicerandom |
last post by:
Hi,
I am currently using the Cmd module for a mixed cli+gui application. I
am starting to refactor my code and it would be highly desirable if
many commands could be built as simple plugins.
My idea was:
- Load a list of plugin names (i.e. from the config file, or from the
plugins directory)
- Import all plugins found dynamically:
|
by: Ray |
last post by:
Hi all,
I am thinking of subclassing the standard string class so I can do
something like:
mystring str;
....
str.toLower ();
A quick search on this newsgroup has found messages by others
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
|
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: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
|
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: 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: 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...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |