classmethod and instance method

  • Thread starter andychambers2002
  • Start date
A

andychambers2002

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
print self

a = A()
a.meth(a)

The above code seems to work as intended. Could the same effect be
achieved using a second decorator in addition to the @classmethod. I
tried

def instancemethod(self):
return self.meth(self)

@instancemethod
@classmethod
def meth(cls, self):
#do stuff

but it didn't work. Any suggestions?

Regards,
Andy
 
X

Xavier Morel

Hi,

I'm trying to write a method that needs to know both the class name and
the instance details

Any suggestions?

What's the point of using a classmethod and an explicit cls argument
when you can get the class object from the instance itself?
def meth(self):
print self
print self.__class__
print type(self)

<__main__.Test object at 0x00FA1710>
 
A

andychambers2002

Yes that's better. Didn't know about the __class__ attribute. I
thought there must be a way to access this but couldn't find it in the
docs.

Thanks,

Andy
 
X

Xavier Morel

Yes that's better. Didn't know about the __class__ attribute. I
thought there must be a way to access this but couldn't find it in the
docs.

Thanks,

Andy
dir(), help() and the interactive interpreter (IDLE or CLI) are your
best friends.

Any time you wonder what an object does, or if you do something to an
object, fire the interpreter, create your object, abuse it via
dir/help/whatever, and then use dir/help/whatever on the results of
dir'ing your object.

Oh, and use new style classes too (explicitly inherit from `object` or a
built-in type), they are much more flexible and interesting than
old-style classes
pass
>>> test = Test()
>>> dir(test) # are completely uninteresting ['__doc__', '__module__']
>>> class Test(object): # new style classes on the other hand
pass
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__module__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__']
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top