[Tutor] class functions/staticmethod?
Steven D'Aprano
steve at pearwood.info
Tue Aug 13 21:15:01 EDT 2019
On Wed, Aug 14, 2019 at 09:58:35AM +1000, Cameron Simpson wrote:
> On 11Aug2019 22:58, James Hartley <jjhartley at gmail.com> wrote:
> >I am lacking in understanding of the @staticmethod property.
> >Explanation(s)/links might be helpful. I have not found the descriptions
> >found in the Internet wild to be particularly instructive.
>
> You have received some answers; to me they seem detailed enough to be
> confusing.
Its only confusing if you don't work your way through it carefully and
systematically. There's a lot to understand, but if you don't understand
it, Python's behaviour in this case seems counter-intuitive and hard to
follow.
Python makes the behaviour of regular instance methods so simple and
intuitive, it can be quite a blow when you try to do something that
isn't.
> I think of things this way: what context does a method require? Not
> everything needs the calling instance.
>
> Here endeth the lesson.
Given that you go on to write almost another 150 lines of explanation, I
think a better description would be "Here *begins* the lesson" *wink*
Your lesson, I think, assumes that it is obvious that staticmethods
don't have access to the calling instance, or its class. But if you look
at James' code, I think you will agree that he's assuming that
staticmethods *do* have access to the calling class, and is perplexed by
the fact that the look-up of class variables (class attributes) fails.
If James comes from a Java background, he's probably assuming that
static methods do have access to the class variables, using undotted
names:
class K(object):
attr = 1
@staticmethod
def foo():
return attr
In Java, K.foo() would return 1.
Your lesson gives us no clue why James' first method, "dimensions()",
which he describes as a "class method", isn't a class method and doesn't
actually work correctly, even though it appears to at first glance.
--
Steven
More information about the Tutor
mailing list