0

I got a bit confused with class methods:

Consider the following example

class A:
    number = 0

    def add_int_n(n: int) -> int:
        return A.number + n

    @classmethod
    def add_int_m(cls, m: int) -> int:
        return cls.number + m

    @staticmethod
    def add_int_k(cls, k: int) -> int:
        return cls.number + k

I notice the former and the last ones are of class function whereas the second is of class method. What are the fundamental differences between the two (if any)?

NPE
  • 464,258
  • 100
  • 912
  • 987
user101
  • 456
  • 4
  • 8
  • @gst Thanks for pointing me to the answer. Do you any best practices when to use methods or functions? – user101 Oct 19 '19 at 17:08
  • Use an instance method if you actually need access to the instance of the class. If you don't, use a static method (although then you should consider whether to use a regular function outside the class; a static method really is just a function living in the class's namesspace). A class method is intended as an alternate constructor; if `A.foo` is a class method, then `A(...)` and `A.foo(...)` should both return instances of `A`. – chepner Oct 19 '19 at 18:41

1 Answers1

0

lookup this video: https://realpython.com/lessons/regular-instance-methods-vs-class-methods-vs-static-methods/ I think you can easyly understand differences.

user2883814
  • 365
  • 2
  • 18