473,724 Members | 2,277 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

@classmethod question

Hi,

I'm using the @classemethod decorator for some convenience methods and for some reason, either mental block or otherwise, can't seem to figure out howto elegantly detect if the call is from an instance or not.

Here's the problem: Within the class definition, 'isinstance' has nothing to compare to because the class does not appear to exist.

This is NOT a great example, but it outlines the the code:

class RecipieClass:
def __init__(self):
pass

@classmethod
def get_ingrendient s(self, recipie_list=No ne):

if isinstnace(self ,RecipieClass):
return self.do_somethi ng_interesting( )
else:
return do_something_bo ring(recipie_li st)

Yes, I can test to see if the param exists, but that makes the call exclusive i.e. I can _only_ call it as an instance or with a parameter.

Why am I doing this?

It is a series of convenience methods, in this case I'm interacting with a database via an ORM (object-relational model). I want the ability to call aclass-ojbect and get related values, or pass some criteria and get relatedvalues for them without collecting the records first as instances, then iterating them. I need to call this from several places so I want to be DRY (don't repeat yourself).

The easiest way to describe this as an analogy would be like having a recipie for cookies and wanting to know all of the ingredients ahead of time. Then, at another time, wanting to know what all the ingredients would be to make cookies, cake and bread (i.e. complete shopping list).

cookie_recipie = RecipieClass.ge t_recipie('cook ies')
cookie_recipie. get_ingredients ()
2C Flour
0.5 C Sugar
...

RecipieClass.ge t_ingrendients(['cookies','cake ','bread'])
8C Flour
2C Sugar
...

Of course any suggestions on how this might be better approached would be interesting too.

TIA,

Scott
Jun 27 '08 #1
3 1264
On 24 ÁÐÒ, 07:27, Scott SA <py...@rscorp.a b.cawrote:
Hi,

I'm using the @classemethod decorator for some convenience methods and forsome reason, either mental block or otherwise, can't seem to figure out howto elegantly detect if the call is from an instance or not.

Here's the problem: Within the class definition, 'isinstance' has nothing to compare to because the class does not appear to exist.

This is NOT a great example, but it outlines the the code:

class RecipieClass:
def __init__(self):
pass

@classmethod
def get_ingrendient s(self, recipie_list=No ne):

if isinstnace(self ,RecipieClass):
return self.do_somethi ng_interesting( )
else:
return do_something_bo ring(recipie_li st)

Yes, I can test to see if the param exists, but that makes the call exclusive i.e. I can _only_ call it as an instance or with a parameter.

Why am I doing this?

It is a series of convenience methods, in this case I'm interacting with adatabase via an ORM (object-relational model). I want the ability to call aclass-ojbect and get related values, or pass some criteria and get related values for them without collecting the records first as instances, then iterating them. I need to call this from several places so I want to be DRY (don't repeat yourself).

The easiest way to describe this as an analogy would be like having a recipie for cookies and wanting to know all of the ingredients ahead of time. Then, at another time, wanting to know what all the ingredients would be to make cookies, cake and bread (i.e. complete shopping list).

cookie_recipie = RecipieClass.ge t_recipie('cook ies')
cookie_recipie. get_ingredients ()
2C Flour
0.5 C Sugar
...

RecipieClass.ge t_ingrendients(['cookies','cake ','bread'])
8C Flour
2C Sugar
...

Of course any suggestions on how this might be better approached would be interesting too.

TIA,

Scott
Hi,
It would make sense to separate instance-level and class-level
behaviour with additional 'objects' namespace. e.g.
cookie_recipie. get_ingredients () to get ingredients only for cookie
recipie and RecipieClass.ob jects.get_ingre ndients([....]) to get all
the ingredients.

The elegant solution (AFAIK used by Django) would be to use metaclass
and the object with custom descriptor for class-object/table level
stuff.

Something like this:

class RecipieMetaclas s(type):
def __new__(cls, bases, attrs):
new_cls = type.__new__(cl s, name, bases, attrs)
new_cls.objects = IngredientsDesc riptor(Ingredie ntsManager())
return new_cls

class RecipieClass(ob ject):
__metaclass__ = RecipieMetaclas s
def get_ingredients (self, recipie_list=No ne):
return self.do_somethi ng_interesting( recipie_list)

class IngredientsMana ger(object):
def get_ingredients (self, recipie_list=No ne):
return do_something_bo ring(recipie_li st)

class IngredientsDesc riptor(object):
def __init__(self, ingredients_man ager):
self.ingredient s_manager = ingredients_man ager
def __get__(self, instance, type=None):
if instance is not None:
raise AttributeError, "Access via %s instances is not
allowed" % type.__name__
return self.ingredient s_manager

Then, "at another time, wanting to know what all the ingredients would
be to make cookies, cake and bread" you would call:
RecipieClass.ob jects.get_ingre ndients(['cookies','cake ','bread'])

Both Django and Google Apps Engine API use similar concepts and you
can learn much more interesting looking in their source code.

Regards,

--
Ivan
Jun 27 '08 #2
Scott SA a écrit :
Hi,

I'm using the @classemethod decorator for some convenience methods
and for some reason, either mental block or otherwise, can't seem to
figure out how to elegantly detect if the call is from an instance or
not.
Well, the point is that a classmethod *always* receive the class as
first argument, wether it's called on the class or an instance. If
that's not what you want, then you don't use the right tool.

Here's the problem: Within the class definition, 'isinstance' has
nothing to compare to because the class does not appear to exist.
>
This is NOT a great example, but it outlines the the code: >
class RecipieClass:
def __init__(self):
pass

@classmethod
def get_ingrendient s(self, recipie_list=No ne):

if isinstnace(self ,RecipieClass):
return self.do_somethi ng_interesting( )
else:
return do_something_bo ring(recipie_li st)

Yes, I can test to see if the param exists, but that makes the call
exclusive i.e. I can _only_ call it as an instance or with a parameter.

Why am I doing this?

It is a series of convenience methods, in this case I'm interacting
with a database via an ORM (object-relational model).
out of curiosity : which one ?
I want the ability
to call a class-ojbect and get related values, or pass some criteria and
get related values for them without collecting the records first as
instances, then iterating them. I need to call this from several places
so I want to be DRY (don't repeat yourself).

The easiest way to describe this as an analogy would be like having a
recipie for cookies and wanting to know all of the ingredients ahead of
time. Then, at another time, wanting to know what all the ingredients
would be to make cookies, cake and bread (i.e. complete shopping list).
cookie_recipie = RecipieClass.ge t_recipie('cook ies')
cookie_recipie. get_ingredients ()
2C Flour
0.5 C Sugar
...

RecipieClass.ge t_ingrendients(['cookies','cake ','bread'])
8C Flour
2C Sugar
...
Of course any suggestions on how this might be better approached
would be interesting too.

Why do you want the same method to do two different things ? You clearly
have two distincts methods doing different things here, and as a user of
your code I'd find your API confusing. May I suggest a much simpler
approach:
class Recipies(object ):
@property
def ingredients(sel f):
return <dict of ingredient:qty for self>

@classmethod
def get_ingredients _for(cls, *id_recipies):
return <dict of ingredient:summ ed_qty for all id_recipies>
print Recipie.get('co okie').ingredie nts
print Recipies.get_in gredients_for(' cookie', 'cake', 'bread')

My 2 cents...
Jun 27 '08 #3
Scott SA <py***@rscorp.a b.cawrites:

A side note
class RecipieClass:
Recipe is a more widespread spelling, I believe. Moreover it is the
convention in python that only class names are capitalized, so you
don't need to append a 'Class'.

class Recipe:
...
clafoutis = Recipe('eggs', 'spam')

--
Arnaud
Jun 27 '08 #4

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

Similar topics

6
1354
by: Zak Arntson | last post by:
I'm currently implementing a game GUI, where there are three components to the screen: A battle, a command button area and a city view area. Each of these are rectangular, and handle interactions in different ways. For example, on the battle "frame" you can select units, right-click to deliver context-sensitive commands, etc. On the command frame, you select buttons to deliver commands, change the state of the battle frame (i.e., a move...
5
17266
by: C Gillespie | last post by:
Hi, Does anyone know of any examples on how (& where) to use staticmethods and classmethods? Thanks Colin
3
2020
by: Giovanni Bajo | last post by:
Hello, what's the magic needed to reuse the base-class implementation of a classmethod? class A(object): @classmethod def foo(cls, a,b): # do something pass
6
1280
by: Laszlo Zsolt Nagy | last post by:
Hello, Is it possible to tell, which instance was used to call the classmethod that is currently running? Background: I have a class called DatabaseConnection and it has a classmethod called process_create_tables. This method should create some database tables defined by a database definition object. The DatabaseConnection has many descendants, for example PostgreSQLConnection. Descendants know how to create tables in a given
3
2142
by: andychambers2002 | last post by:
Hi, I'm trying to write a method that needs to know both the class name and the instance details class A: @classmethod def meth(cls, self): print cls
2
1389
by: Sylvain Ferriol | last post by:
hello can you explain why python does not see difference between instance method and class method, having the same name example .... def f(self): .... print('instance method') .... @classmethod .... def f(cls): .... print('class method')
14
2731
by: james_027 | last post by:
hi, python's staticmethod is the equivalent of java staticmethod right? with classmethod, I can call the method without the need for creating an instance right? since the difference between the two is that classmethod receives the class itself as implicti first argument. From my understanding classmethod are for dealing with class attributes? Can somebody teach me the real use of classmethod & staticmethod?
3
2379
by: Matthew Keene | last post by:
I would like to be able to call a specific classmethod on a class name that is going to be passed from another parameter. In other words, I have a call that looks something like: x = Foo.bar() and I would like to generalise this so that I can make this call on any particular class which provides the bar classmethod. I have implemented this using exec, like so:
0
1447
by: Gabriel Genellina | last post by:
En Thu, 24 Apr 2008 00:27:13 -0300, Scott SA <pydev@rscorp.ab.caescribió: Then you can't use a classmethod. A class method can *only* be called on the defining class or a subclass of it, or using an instance of those classes, but in any case the first argument (usually called "cls", not "self") is the *class* on which you called it. I'm not sure if I get the idea right, but it looks like two different
0
9241
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8062
agi2029
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...
1
6685
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5996
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();...
0
4504
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...
0
4764
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3209
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
2
2612
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2149
bsmnconsultancy
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...

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.