I have a class factory problem. You could say that my main problem is
that I don't understand class factories.
My specific problem:
I have a class with several methods I've defined.
To this class I want to add a number of other class methods where the
method names are taken from a list.
For each list member, I want to build a method having the list member
name so that I can override another method of the same name for objects
which are instances of this class. Finally, I want my class factory
which creates the method to call the overridden method.
I'm sure my description is confusing, so I'll try to illustrate it.
import Numeric
# The Numeric module contains a whole lot of methods which operate on
certain number types
class foo:
""" this is a number type class
"""
def __init__(self, value):
self.value = float(value)
def __str__(self): 5 1735
Thanks for the very helpful reply Rainer,
I thought I couldn't use setattr because I need the syntactic sugar
sqrt(f) to work, but with your example code Numeric.sqrt(f) does in fact
work correctly. I also need to do a bit more than may be possible with a
simple lambda function, but I should be able to sort it out from here
with the info you provided,
thanks again,
Gary
Rainer Mansfeld wrote:
<snip> Hi Gary,
you want your 'class factory' to change the methods of Numeric, so that they accept foo objects and return foo objects? I've not the slightest idea how to achieve that.
If OTOH you want your foo class to have sqrt, arccos, etc. methods without defining them explicitly, I think you're looking for something like:
. import Numeric . . class Foo(object): . def __init__(self, value): . self.value = float(value) . for u in ['sqrt', 'cos', 'tan']: . setattr(self, u, lambda uf=getattr(Nume ric, u): . uf(self.value + 42.0))
>>> f = Foo(7) >>> f.sqrt()
7.0
HTH Rainer
OK, I've managed to get this to work with Rainer's method, but I
realised it is not the best way to do it, since the methods are being
added by the constructor, i.e. they are instance methods. This means
that every time a foo object is created, a whole lot of code is being
run. It would be better to do the same thing with class 'static'
methods, if this is possible, so that the methods are created just once.
Is this possible?
Gary
Rainer Mansfeld wrote:
<snip> If OTOH you want your foo class to have sqrt, arccos, etc. methods without defining them explicitly, I think you're looking for something like:
. import Numeric . . class Foo(object): . def __init__(self, value): . self.value = float(value) . for u in ['sqrt', 'cos', 'tan']: . setattr(self, u, lambda uf=getattr(Nume ric, u): . uf(self.value + 42.0))
>>> f = Foo(7) >>> f.sqrt()
7.0
HTH Rainer
Gary Ruben wrote: OK, I've managed to get this to work with Rainer's method, but I realised it is not the best way to do it, since the methods are being added by the constructor, i.e. they are instance methods. This means that every time a foo object is created, a whole lot of code is being run. It would be better to do the same thing with class 'static' methods, if this is possible, so that the methods are created just once. Is this possible?
See my comment on the recipe at: http://aspn.activestate.com/ASPN/Coo.../Recipe/389793
STeVe
Gary Ruben wrote: OK, I've managed to get this to work with Rainer's method, but I realised it is not the best way to do it, since the methods are being added by the constructor, i.e. they are instance methods. This means that every time a foo object is created, a whole lot of code is being run. It would be better to do the same thing with class 'static' methods, if this is possible, so that the methods are created just once. Is this possible?
Here is a solution using a metaclass:
import Numeric
class MetaFoo(type):
def __init__(cls, name, bases, d):
super(MetaFoo, cls).__init__(c ls, name, bases, d)
for u in ['sqrt', 'cos', 'tan']:
setattr(cls, u, lambda self, uf=getattr(Nume ric, u): uf(self.value + 42.0))
class Foo(object):
__metaclass__ = MetaFoo
def __init__(self, value):
self.value = float(value)
f = Foo(7)
print f.sqrt()
Kent
Thanks Steven and Kent, both of your suggestions look good to me. I'll
try both out and pick one.
Gary
Gary Ruben wrote: OK, I've managed to get this to work with Rainer's method, but I realised it is not the best way to do it, since the methods are being added by the constructor, i.e. they are instance methods. This means that every time a foo object is created, a whole lot of code is being run. It would be better to do the same thing with class 'static' methods, if this is possible, so that the methods are created just once. Is this possible? Gary This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Carlos Ribeiro |
last post by:
I thought about this problem over the weekend, after long hours of
hacking some metaclasses to allow me to express some real case data
structures as Python classes. I think that this is something with
potential to be useful, but I would like to hear more opinions first.
If this is deemed to be useful, I *may* try to write a PEP for it.
This is not a promise or even a proposal, at this point.
Broadly generalizing, classes in Python have...
|
by: Johan Bergman |
last post by:
Hi,
Maybe someone can help me with this one. The following describes a
somewhat simplified version of my problem, but I think it will be
sufficient.
I want to use class factories (virtual constructors) which have this base
class:
template<class T>
|
by: Aguilar, James |
last post by:
My previous example used the concept of a Shape class heirarchy, so I will
continue with that.
Suppose I have something like fifty different shapes, and I am trying to
instantiate one of them. The trick is, the instatiation will be based on a
string with the exact same name as the type that I am trying to instantiate.
Obviously, writing a fifty element long switch statement is an inferior
solution. So, how can I instantiate based on...
|
by: Patrick Stinson |
last post by:
I am trying to create a way to register static members of a **class**, not
an object, for making an object factory. The main thing I want is to be
able to make a call like
class MyClass
{
public:
MyClass *factory();
};
register(MyClass);
|
by: Jon Rea |
last post by:
I hav been looking for the last 2 hours on how to do this without much luck.
Im going to give a simplifed model of the problem i have.
I want a collection class that can holds a series or objects, for arguments
sake, lets make these fruit :
apple
orange
bannana
| |
by: Craig Buchanan |
last post by:
I've seen design patterns for class factories that work well to create
(fetch) objects, but I haven't seen anything about how to persist the class'
data when it has changed. Is this done thru the factory? What about
security? I'm assuming that the factory should enforce security.
Has anyone seen examples of this?
Thanks,
Craig Buchanan
|
by: deko |
last post by:
Which layer should a Factory class go in?
DA - Data Access
BL - Business Logic
UI - User Interface
??
|
by: docschnipp |
last post by:
Hi,
I have a bunch of object derived from the same base class. They all share
the same constructor with some parameters. Now, instead of using a large
switch() statement where I call every single Object by itself, I'd like to
assign a reference to the class type and call it later without knowing the
derived type.
Example:
|
by: =?Utf-8?B?cml2YWxAbmV3c2dyb3Vwcy5ub3NwYW0=?= |
last post by:
Morning,
I've got an ASP.NET 2.0 Web Application. Behind it, I've a
statically-scoped facade/class factory as the business layer, running atomic
functions back and forth from my by DAL.
The DAL returns DataSet objects to the facade, which loads the data into a
memento object to pass to the ASP.NET interface.
For instance, I've got the method Profile ProfileSystem.GetProfile(Guid
|
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
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 most users, this new feature is actually very convenient. If you want to control the update process,...
| |
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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 launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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 into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
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: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |