- What is a class in Python, and how is it defined?
- What is the difference between a class and an object in Python?
- What is inheritance in Python OOP, and how does it work?
- What is polymorphism in Python OOP, and how is it achieved?
- Can you explain the difference between method overriding and method overloading in Python?
- What is the difference between class attributes and instance attributes in Python?
- How would you implement a singleton class in Python?
- Can you explain the difference between the
__str__
and__repr__
methods in Python classes? - What is a property in Python, and how is it defined and used?
- Can you explain the difference between deep and shallow copying in Python?
These questions will help you assess a candidate’s understanding of OOP concepts in Python and their ability to apply them in practice.
the difference between the __str__ and __repr__ methods in Python classes?
In Python, the __str__
and __repr__
methods are used to define the string representation of an object. The main difference between these two methods is the purpose for which they are used.
__str__
is used to define the string representation of an object that is meant to be human-readable. This method should return a string that, when printed, provides a meaningful representation of the object that can be understood by a human. For example:
class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"Person(name={self.name}, age={self.age})" person = Person("John Doe", 30) print(person) # Output: Person(name=John Doe, age=30)
__repr__
is used to define the string representation of an object that is meant to be unambiguous and usable for debugging. This method should return a string that, when passed to the eval()
function, creates an object that is equal to the original. For example:
class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f"Person('{self.name}', {self.age})" person = Person("John Doe", 30) print(repr(person)) # Output: Person('John Doe', 30)
In general, it’s a good idea to implement both __str__
and __repr__
for your classes, so that you can control the string representation of your objects in both human-readable and unambiguous forms.