Bird
0
0

Which of the following correctly defines a method named greet that uses self in a Python class?

easy📝 Syntax Q3 of 15
Python - Constructors and Object Initialization
Which of the following correctly defines a method named greet that uses self in a Python class?
Adef greet():<br> print('Hello')
Bdef greet(self):<br> print('Hello')
Cdef greet(cls):<br> print('Hello')
Ddef greet(self, cls):<br> print('Hello')
Step-by-Step Solution
Solution:
  1. Step 1: Method definition in classes

    Instance methods must have self as the first parameter to access instance data.
  2. Step 2: Analyze options

    def greet(self):
    print('Hello') correctly defines greet(self). def greet():
    print('Hello') lacks self. def greet(cls):
    print('Hello') uses cls which is for class methods. def greet(self, cls):
    print('Hello') has extra parameter cls unnecessarily.
  3. Final Answer:

    def greet(self):
    print('Hello')
    -> Option B
  4. Quick Check:

    Instance methods always include self as first parameter [OK]
Quick Trick: Instance methods always start with self parameter [OK]
Common Mistakes:
  • Omitting self in method parameters
  • Confusing self with cls
  • Adding extra unnecessary parameters

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes