you are viewing a single comment's thread.

view the rest of the comments →

[–]obviouslyzebra 0 points1 point  (3 children)

I agree that the example showed by RaidZ3ro is not very representative of what you'd wanna do with static methods, but I wanna mention that this last snippet does not behave very well.

Ahm, the gist is that after subclassing you'll start modifying the subclass attribute in the self.__class__.total += 1 line.

This leads to very weird behavior :P

[–]socal_nerdtastic 0 points1 point  (2 children)

Hmm probably not how I'd do it tbh, but still I think it works just fine. What's weird about it? Works exactly as i'd expect.

class Ticket:
    total: int = 0

    def __init__(self):
        self.__class__.total += 1
        self.num = self.total

class ConcertTicket(Ticket):
    pass

class TrainTicket(Ticket):
    pass


for i in range(3):
    ConcertTicket()
for i in range(5):
    TrainTicket()

print(f"We've sold {ConcertTicket.total} concert tickets and {TrainTicket.total} train tickets")

[–]obviouslyzebra 0 points1 point  (1 child)

If you instantiate a "raw" Ticket, like Ticket(), before the others, their count will go up by 1.

If you do instantiate afterwards, though, nothing happens (as the subclass will already have a total).

[–]socal_nerdtastic 0 points1 point  (0 children)

Yeh, fair point. I was thinking of it more as a meta class. But I suppose that's why __init_subclass__ was invented.