logo

Python - FAQ

Last Updated: 2024-01-20

How to check types in Python?

Use type():

>>> type('a')
<class 'str'>

Use isinstance():

>>> isinstance(1, int)
True

How to check if a class is a child of another class?

Suppose you have a Parent class and a Child class. issubclass() returns a bool to indicate if Child is a subclass of Parent.

issubclass(Child, Parent)

What is self in Python?

self: represents the instance of the class. It MUST be provided as the first argument in constructor and instance method.

What is __init__ in Python?

__init__ is the constructor. It is called when a new object is created.

Does Python have garbage collection?

Yes.

What are decorators in Python?

Decorators: functions that add functionality to an existing function.

What are generators in Python?

Generators: functions that return an iterable collection of items. Generators use yield instead of return. Calling __next__() will get the next value.

What are iterators in Python?

Iterators: objects with the following methods:

  • __iter__(): initializes an iterator.
  • __next__(): returns the next item.

What are negative indexes?

Negative indexes are the indexes from the end of the sequence.

How to copy an object in Python?

Use (shallow) copy() and deepcopy() from copy.

Assignment statement (=) does NOT make copies.

What is pickle in Python?

pickle module is used for serialization and deserialization:

  • serialization: pickle.dump()
  • deserialization: pickle.load()

How to add additional directories for modules and packages?

Use PYTHONPATH env variable.

What's the difference between .py and .pyc files?

  • .py files: source code.
  • .pyc files: compiled bytecode. Only created for imported files.

How to access parent members?

Use super().

How to specify private or protected members?

Python does NOT have the keywords like public, protected, private. They can be achieved by:

  • public: default.
  • protected: single underscore (_) prefix.
  • private: double underscore(__) prefix.

How to define a main function?

Unlike C++ or Java, Python does not have a main() function as the entry point of execution. A main function can be achieved by checking if __name__ == "__main__":.

How to take a variable number of arguments?

def func(*var):
    for i in var:
        # ...