Python - Versus
Python: arrays vs lists vs tuples
Arrays can only contain elements of the same type; lists and tuples can have different data types.
- Array:
array.array(); a thin wrapper around C language arrays and consumes less memory than lists. - List:
[], mutable. - Tuple:
(), immutable.
Python: property vs attribute
- 2 types of attributes:
- Class Attribute: unique to each class. Each instance of the class will have this attribute. Defined directly in the class body.
- Instance Attribute: unique to each instance. Defined using
selflikeself.foo.
- Property: a special kind of attribute: an attribute with
__get__,__set__and__delete__methods. Created using eitherproperty()or@property.
Python: globals() vs locals() vs vars()
globals()always returns the dictionary of the module namespace.locals()always returns a dictionary of the current namespace.vars()returns either a dictionary of the current namespace (if called with no argument) or the dictionary of the argument.
Python: @staticmethod vs @classmethod
- normal method: the object instance is passed as the first argument
def foo(self, x):
@classmethodmethod: the class is passed as the first argumentdef class_foo(cls, x):(clsis the class)
@staticmethodmethod: no object or class is passed to the method, just like a plain function. It knows nothing about the class or the instance. It is a way of putting a function into a class.def static_foo(x):