473,578 Members | 3,235 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Re: @classmethod question

En Thu, 24 Apr 2008 00:27:13 -0300, Scott SA <py***@rscorp.a b.caescribió:
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.

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):
def get_ingrendient s(self, recipie_list=No ne):
if isinstnace(self ,RecipieClass):
return self.do_somethi ng_interesting( )
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.
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.
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 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.
I'm not sure if I get the idea right, but it looks like two different
classes to me, a Recipe and a RecipeSet:

class Recipe:
def __init__(self, recipe_name)
"""a Recipe given its name"""

def get_ingredients (self)
"""a list of ingredients for this recipe"""

class RecipeSet:
def __init__(self, recipe_names):
"""a set of recipes considered together"""
self.recipe_nam es = recipe_names

def get_ingredients (self)
"""a summarized list of ingredients
for all given recipes"""
cookie_recipie = Recipe('cookies ')
cookie_recipie. get_ingredients ()
2C Flour
0.5 C Sugar
all_ingredients = RecipeSet(['cookies','cake ','bread']).get_ingrendie nts()
8C Flour
2C Sugar

Gabriel Genellina

Jun 27 '08 #1
0 1430

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

Similar topics

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...
by: C Gillespie | last post by:
Hi, Does anyone know of any examples on how (& where) to use staticmethods and classmethods? Thanks Colin
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
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...
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
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')
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...
by: Scott SA | last post by:
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...
by: Scott SA | last post by:
On 4/24/08, Bruno Desthuilliers (bruno.42.desthuilliers@websiteburo.invalid) wrote: I'm rapidly becoming a "django junkie"^TM In retrospect, my example was poorer than I first thought - or was it my spec. Regardless, it wasn't quite right. The question/premise should have been:
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: 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: 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: 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...

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.