3 ms·
My experience with Python is a little lacking, but doesn't the self keyword mean the difference between an instance method, and a static method? Rust does the
by timw4mail 7y ago
My experience with Python is a little lacking, but doesn't the self keyword mean the difference between an instance method, and a static method?
Rust does the same thing - with self, it's an instance method, without, it's a static method.
- dfinninger 7y agoPython has an "@staticmethod" decorator you can put on a function inside of a class definition. Then you don't need to pass "self" as a first arg. https://www.geeksforgeeks.org/class-method-vs-static-method-python/ https://www.geeksforgeeks.org/class-method-vs-static-method-...
- int_19h 7y ago"self" is not a keyword in Python, just a convention. Any function inside a class declaration becomes an instance method, with its first argument becoming the explicit receiver. You have to use @staticmethod to prevent that (or @classmethod to get the class as the first argument, instead of the instance). Furthermore, this behavior is not parse-time, but runtime. The "def" statement that defines a function produces a plain function object, regardless of whether it's inside a class or not. Once the class finishes defining, the function is still a function - which is why C.f gives you a plain instance that can be called by passing "self" explicitly as an argument. However, Python allows objects to provide special behavior for themselves whenever they're retrieved via a member of some class - that is, when you write something like x.y, after y is retrieved from x, it gets the opportunity to peek at x, and substitute itself with something else. Function objects in Python (here I mean specifically the type of objects created with "def" and "lambda", not just any callable) use this feature to convert themselves to bound methods. So, when you say x.f, after retrieving f, f itself is asked if it wants to substitute something else in its place - and it returns a new callable object m, such that m(y) calls f(x, y). That's what makes x.f(y) work.