473,406 Members | 2,217 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,406 software developers and data experts.

adding a static class to another class

HI,

I m trying to start an api in a similar way to the djangic way of
Class.objects.all(). Ie objects is a "Manager" class.

So:

class Foo(object):
def __init__(self):
self.test = "NEE"

class Manager(object):
def __init__(self):
pass
def all(self):
return "COCONUTS"

Because of how some of the code is set up I cant use
metaclasses........so I try to use a decorator:

def addto(instance):
def decorator(f):
import new
f = new.instancemethod(f, instance, instance.__class__)
setattr(instance, "objects", f)
return f
return decorator

class Manager(object):
@addto(Foo)
def __init__(self):
.............

however this only binds the init method to the Foo.objects, so not
what I want. If I try using classmethod...then it just says the
Foo.objects doesnt exist.

Does anyone have any ideas how I can accomplish this using decorators?
And also preventing more than one Manager instance instantiated at one
time.

Many Thanks in advance,

Nathan
Sep 16 '07 #1
5 1277
On Sep 17, 1:14 am, "Nathan Harmston" <ratchetg...@googlemail.com>
wrote:
HI,

I m trying to start an api in a similar way to the djangic way of
Class.objects.all(). Ie objects is a "Manager" class.

So:

class Foo(object):
def __init__(self):
self.test = "NEE"

class Manager(object):
def __init__(self):
pass
def all(self):
return "COCONUTS"

Because of how some of the code is set up I cant use
metaclasses........so I try to use a decorator:

def addto(instance):
def decorator(f):
import new
f = new.instancemethod(f, instance, instance.__class__)
setattr(instance, "objects", f)
return f
return decorator

class Manager(object):
@addto(Foo)
def __init__(self):
.............

however this only binds the init method to the Foo.objects, so not
what I want. If I try using classmethod...then it just says the
Foo.objects doesnt exist.

Does anyone have any ideas how I can accomplish this using decorators?
And also preventing more than one Manager instance instantiated at one
time.

Many Thanks in advance,

Nathan
You want to use descriptors (classes that implement __get__, __set__,
__del__). Google for the particulars.

-- bjorn

Sep 16 '07 #2
Nathan Harmston wrote:
HI,

I m trying to start an api in a similar way to the djangic way of
Class.objects.all(). Ie objects is a "Manager" class.

So:

class Foo(object):
def __init__(self):
self.test = "NEE"

class Manager(object):
def __init__(self):
pass
def all(self):
return "COCONUTS"

Because of how some of the code is set up I cant use
metaclasses........so I try to use a decorator:

def addto(instance):
def decorator(f):
import new
f = new.instancemethod(f, instance, instance.__class__)
setattr(instance, "objects", f)
return f
return decorator

class Manager(object):
@addto(Foo)
def __init__(self):
.............

however this only binds the init method to the Foo.objects, so not
what I want. If I try using classmethod...then it just says the
Foo.objects doesnt exist.

Does anyone have any ideas how I can accomplish this using decorators?
And also preventing more than one Manager instance instantiated at one
time.

Many Thanks in advance,

Nathan
What you are trying to do is a little obscure to me, but I think you
want want to rebind Foo.objects to a new manager every time you
instantiate a Manager? This will do it:

class Foo(object):
def __init__(self):
self.test = "NEE"

class Manager(object):
def __init__(self):
pass
def all(self):
return "COCONUTS"

def addto(cls):
def decorator(f):
def _f(self, *args, **kwargs):
cls.objects = self
f(self, *args, **kwargs)
return _f
return decorator

class Manager(object):
@addto(Foo)
def __init__(self):
pass

Example:

pyclass Foo(object):
.... def __init__(self):
.... self.test = "NEE"
....
pyclass Manager(object):
.... def __init__(self):
.... pass
.... def all(self):
.... return "COCONUTS"
....
pydef addto(cls):
.... def decorator(f):
.... def _f(self, *args, **kwargs):
.... cls.objects = self
.... f(self, *args, **kwargs)
.... return _f
.... return decorator
....
pyclass Manager(object):
.... @addto(Foo)
.... def __init__(self):
.... pass
....
pyhasattr(Foo, 'objects')
False
pym = Manager()
pyprint m
<__main__.Manager object at 0x121b870>
pyprint Foo.objects
<__main__.Manager object at 0x121b870>
pyn = Manager()
pyprint n
<__main__.Manager object at 0x121b250>
pyprint Foo.objects
<__main__.Manager object at 0x121b250>
If you just want the class Foo to have the class Manager as its objects,
just do this:

Foo.objects = Manager

But I don't think that's what you want.

I'm not familiar with django, so if I haven't hit it, please elaborate.

James

Sep 17 '07 #3
Nathan Harmston wrote:
And also preventing more than one Manager instance instantiated at one
time.
Forgot to answer this. You want the singleton pattern:

http://aspn.activestate.com/ASPN/Coo...n/Recipe/52558

James
Sep 17 '07 #4
James Stroud wrote:
Nathan Harmston wrote:
>And also preventing more than one Manager instance instantiated at one
time.

Forgot to answer this. You want the singleton pattern:

http://aspn.activestate.com/ASPN/Coo...n/Recipe/52558
But not really a singleton now that I think about it...

class Singletonish(object):
""" A python singletonish """

class __impl(object):
""" Implementation of the singletonish interface """

def spam(self):
""" Test method, return singletonish id """
return id(self)

# storage for the instance reference
__instance = None

def __init__(self):
""" Create singletonish instance """
Singletonish.__instance = Singletonish.__impl()

def __getattr__(self, attr):
""" Delegate access to implementation """
if attr == '__id__':
return id(Singletonish.__instance)
return getattr(Singletonish.__instance, attr)

def __setattr__(self, attr, value):
""" Delegate access to implementation """
return setattr(Singletonish.__instance, attr, value)
In action:

pyclass Singletonish(object):
.... """ A python singletonish """
.... class __impl(object):
.... """ Implementation of the singletonish interface """
.... def spam(self):
.... """ Test method, return singletonish id """
.... return id(self)
.... # storage for the instance reference
.... __instance = None
.... def __init__(self):
.... """ Create singletonish instance """
.... Singletonish.__instance = Singletonish.__impl()
.... def __getattr__(self, attr):
.... """ Delegate access to implementation """
.... return getattr(Singletonish.__instance, attr)
.... def __setattr__(self, attr, value):
.... """ Delegate access to implementation """
.... return setattr(Singletonish.__instance, attr, value)
....
pys = Singletonish()
pyprint s.spam()
18727248
py>
pyt = Singletonish()
pyprint t.spam()
18682480
pyprint s.spam()
18682480
Of course t and s are not /really/ the same:
pyprint id(t)
18727056
pyprint id(s)
18727280
pyassert t is s
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
<type 'exceptions.AssertionError'>
But this shouldn't matter unless you have a special use case because the
implementation to all Singletonish objects are delegated to to the
latest __impl object and so behave identically.

James
Sep 17 '07 #5
Nathan Harmston a écrit :
HI,

I m trying to start an api in a similar way to the djangic way of
Class.objects.all(). Ie objects is a "Manager" class.

So:

class Foo(object):
def __init__(self):
self.test = "NEE"

class Manager(object):
def __init__(self):
pass
def all(self):
return "COCONUTS"

Because of how some of the code is set up I cant use
metaclasses........so I try to use a decorator:

def addto(instance):
def decorator(f):
import new
f = new.instancemethod(f, instance, instance.__class__)
setattr(instance, "objects", f)
return f
return decorator

class Manager(object):
@addto(Foo)
def __init__(self):
.............

however this only binds the init method to the Foo.objects, so not
what I want.
Indeed.
If I try using classmethod...then it just says the
Foo.objects doesnt exist.
You mean decorating Manager.__init__ with classmethod ???

I may be wrong, but I suspect you don't have a clear idea of what you're
doing here.
Does anyone have any ideas how I can accomplish this using decorators?
Yes : don't use a decorator !-)

Instead of asking for how to implement what you think is the solution,
you might be better explaining the problem you're trying to solve.
And also preventing more than one Manager instance instantiated at one
time.
Q&D:

class Singleton(object):
def __new__(cls):
if not hasattr(cls, '_inst'):
cls._inst = object.__new__(cls)
return cls._inst
Same remark as above...
Sep 17 '07 #6

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

Similar topics

2
by: John Carson | last post by:
One routinely hears that the order of initialisation of objects with static storage duration in different translation units cannot in general be guaranteed. I have a question about one way to...
15
by: Samee Zahur | last post by:
Question: How do friend functions and static member functions differ in terms of functionality? I mean, neither necessarily needs an object of the class to be created before they are called and...
3
by: Jae | last post by:
Hello, here's what I want to do but I'm not sure if it will work because Im not sure how DB2 works with the JVM. Heres my setup: DB2---->UDF Class (lets call it A)----->Static Class (Lets call...
13
by: Rob Meade | last post by:
Hi all, I have written a small ProperCase function which I would like to make available to our team at work through our common class library. A colleague mentioned that I could write a new...
3
by: MIGUEL | last post by:
Hi all, I'm quite lost with how adding web references to a project creates proxy classes. I've developed a web service with two classes inside and that contains three references to three...
11
by: Kevin Prichard | last post by:
Hi all, I've recently been following the object-oriented techiques discussed here and have been testing them for use in a web application. There is problem that I'd like to discuss with you...
5
by: Water Cooler v2 | last post by:
I know that we can add a single name value entry in app.config or web.config in the configuration/configSettings/appSettings section like so: <add key="key" value="value" /> Question: I want...
7
by: Jo | last post by:
Hi, How can i differentiate between static and dynamic allocated objects? For example: void SomeFunction1() { CObject *objectp = new CObject; CObject object;
55
by: Zytan | last post by:
I see that static is more restricted in C# than in C++. It appears usable only on classes and methods, and data members, but cannot be created within a method itself. Surely this is possible in...
3
by: raylopez99 | last post by:
Oh, I know, I should have provided complete code in console mode form. But for the rest of you (sorry Jon, just kidding) I have an example of why, once again, you must pick the correct entry point...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
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...
0
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...
0
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...
0
Oralloy
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,...
0
jinu1996
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...
0
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...
0
tracyyun
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...
0
isladogs
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...

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.