[Tutor] class functions/staticmethod?

Cameron Simpson cs at cskk.id.au
Tue Aug 13 21:38:53 EDT 2019


On 14Aug2019 11:15, Steven D'Aprano <steve at pearwood.info> wrote:
>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.

Yeah, but it helps to understand the objective: function context.

A deep dive into the mechanisms used to achieve that is a load to 
ingest. High levels of detail tend to swamp one's view of the larger 
picture, particularly when learning.

[...]
>> 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*

Well, maybe, but I really wanted to highlight the objective: 
@classmethod and @staticmethod dictate the context provided to the 
method.

All the examples that follow aim, however vaguely, to show those 
contexts in action.

>Your lesson, I think, assumes that it is obvious that staticmethods
>don't have access to the calling instance, or its class.

No, it aims to make that point clear. EVerything else is example or 
mechanism.

>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.

Because nobody had said that @staticmethod and @classmethod _define_ the 
provided context.

>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.

I didn't try to tackle his code. I think it is better to get the 
intended use of @classmethod and @staticmethod clear. Digging into 
whatever weird consequences there might be to his slightly wrong code 
just brings confusion.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list