Correct answers B & D.
A. is incorrect - the first parameter of __init__ is conventionally named self, but it can be named anything (though it's strongly recommended to use self for readability)
C. is incorrect - the constructor (__init__) can be invoked directly, though it's not common; for example, MyClass.__init__(obj, args...) is technically valid but not recommended
B and D are correct answers.
A) False
class MyClass:
def __init__(this, value): # Using 'this' instead of 'self'
this.value = value
obj = MyClass(10)
print(obj.value) # Output: 10
B) True
class MyClass:
def __init__(self):
pass
def __init__(self, value):
self.value = value
obj1 = MyClass() # Error
obj2 = MyClass(20)
print(obj2.value) # Output: 20
C) False
class MyClass:
def __init__(self, value):
self.value = value
obj = MyClass.__init__(MyClass, 10) # Error
obj = MyClass.__init__(10) # Error
D) True
class MyClass:
def __init__(self, value):
self.value = value
return "This will cause an error"
obj = MyClass(10) # This will raise a TypeError: __init__() should return None, not 'str'
A voting comment increases the vote count for the chosen answer by one.
Upvoting a comment with a selected answer will also increase the vote count towards that answer by one.
So if you see a comment that you already agree with, you can upvote it instead of posting a new comment.
Horsefeathers
6 days, 9 hours agokino_1994
5 months, 2 weeks agokino_1994
5 months, 2 weeks agokstr
6 months, 3 weeks agoDKAT2023
6 months, 3 weeks ago