logo

Python - Versus

Last Updated: 2024-01-20

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 self like self.foo.
  • Property: a special kind of attribute: an attribute with __get__, __set__ and __delete__ methods. Created using either property() 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):
  • @classmethod method: the class is passed as the first argument
    • def class_foo(cls, x): (cls is the class)
  • @staticmethod method: 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):