Challenge your understanding of Python classes with these multiple-choice questions. Perfect for beginners to practice key concepts like class creation, object instances, constructors, and methods in Python.
Watch this video for the answer: https://youtu.be/zVYzk_gnTY4
Answer: a) class MyClass:
class Dog:
name = "Unknown"
def bark(self):
print("Woof!")
dog1 = Dog()
dog1.name = "Buddy"
dog2 = Dog()
print(dog1.name, dog2.name)
class Test:
def __init__(self, x):
self.x = x
t = Test(5)
print(t.x)
class Dog:
species = "Canis familiaris"
def __init__(self, name):
self.name = name
d = Dog("Buddy")
- A) `name`
- B) `species`
- C) `__init__`
- D) `Dog`
class Car:
wheels = 4 # Class attribute
def __init__(self, color):
self.color = color # Instance attribute
car1 = Car("Red")
car2 = Car("Blue")
Car.wheels = 6
print(car1.wheels)
print(car2.wheels)
4
4
B)
6
6
C)
4
6
D) Error
__init__
method.Correct Answer: C.
Explanation: Class attributes are shared across all instances. Instance attributes are unique to each object.
class Item:
category = "Grocery"
def __init__(self, name):
self.name = name
item1 = Item("Soap")
item1.category = "Cosmetic"
print(Item.category)
print(item1.category)
A)
Grocery
Cosmetic
B)
Cosmetic
Cosmetic
C)
Cosmetic
Grocery
D) Error