Bird
0
0

How can you list all public attributes of an object obj in Python?

hard📝 Application Q9 of 15
Python - Encapsulation and Data Protection
How can you list all public attributes of an object obj in Python?
AUse obj.get_public_attributes() method
BUse obj.__dict__ directly without filtering
CUse [attr for attr in dir(obj) if not attr.startswith('_')]
DUse dir(obj) without filtering
Step-by-Step Solution
Solution:
  1. Step 1: Understand how to get attributes of an object

    dir(obj) lists all attributes including private and special ones.
  2. Step 2: Filter out private and special attributes

    Attributes starting with underscore are private or special, so filtering them out leaves public attributes.
  3. Final Answer:

    Use [attr for attr in dir(obj) if not attr.startswith('_')] -> Option C
  4. Quick Check:

    Filter dir() to exclude underscore-prefixed attributes [OK]
Quick Trick: Filter dir() to exclude names starting with underscore [OK]
Common Mistakes:
  • Using dir() without filtering
  • Assuming __dict__ only has public attributes
  • Expecting a built-in get_public_attributes() method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes