I started learning python over ten years ago in an informal setting. The way I've learned seem to have been whatever I saw on StackOverflow and whatever I saw people doing around me. I've not felt like I've had a solid grasp of the more advanced concepts - I appear to have skillfully bumbled along for ten years. After doing some review yesterday, here is a list of things that I must have read and then promptly forgotten at some point:
self: this references the current instance. When this is the first argument in the method, we can access all other instance variables and methods. I've always used this without thinking.
classmethod: the `@classmethod` decorator modifies a function inside a class (or, a method) to take in `cls` as an argument (convention). This lets us define alternative constructors i.e. feed arguments packaged differently into `__init__` in re-usable ways packed with the class e.g. unpacking a tuple. This also accesses class-level data.
staticmethod: the `@staticmethod` decorator modifies the method such that it behaves like a normal function, but is packaged with the class because it is called so often. `self` is not one of its arguments, hence 'normal function'.
getter setter: we use these to protect the class states from outside access. Why I would ever use this is mysterious to me, but setter methods allow you to do internal validation and throw errors if needed.
__len__, __getitem__: When reading Fluent Python they discussed how `len` was like a special unary operator. Default python data-types and numpy objects have their length stored in their C objects and can be retrieved very quickly. On the other hand, `getitem` allows us to use the `[]` square brackets to index our class, which can be very powerful - we can access the class objects like a list, allowing us to iterate and slice.
No comments:
Post a Comment