Explore the fundamentals of Python's class and object system with straightforward questions ideal for those beginning backend development. Get familiar with key concepts, syntax, and best practices.
Which keyword is used to define a class in Python?
Explanation: The 'class' keyword is specifically used for defining new classes in Python. 'def' is used to define functions, and 'func' is not a recognized Python keyword for declaring classes or functions.
What is the correct way to create an object from a class named Car?
Explanation: 'my_car = Car()' correctly creates an instance of Car and assigns it to my_car. 'my_car == Car' is a comparison, not object creation, and 'Car(my_car)' attempts to pass an argument to Car, which may not be necessary.
Where are instance attributes typically initialized in a Python class?
Explanation: Instance attributes are usually initialized inside the '__init__' method for each object. Declaring them outside any method makes them class attributes, and defining them in the main program does not associate them with the class instance.
How do you call a method named drive on an object car?
Explanation: 'car.drive()' is the correct syntax for calling a method on an object. 'drive.car()' and 'car->drive()' are invalid in Python; the arrow syntax is common in other languages like C++.
Why is self used in method definitions of a Python class?
Explanation: 'self' refers to the current instance of the class inside instance methods. It is not used for importing modules, and static methods do not require 'self' as a parameter.
Which attribute changes value for every object instance?
Explanation: An instance attribute belongs to each object separately, allowing different values per instance. Class attributes are shared across all instances, and 'static attribute' is not a common Python term.
How do you define a class Bike that inherits from Vehicle?
Explanation: Inheritance in Python is declared using the syntax 'class Bike(Vehicle):'. The other options do not follow Python's inheritance syntax.
Which method is called when an object is about to be destroyed in Python?
Explanation: '__del__' is the destructor method automatically called when an object is about to be deleted. '__init__' is used for initialization, and '__create__' is not a standard Python method.