- This topic is empty.
-
AuthorPosts
-
November 30, 2025 at 11:51 pm #5805
❓ Question:
In the code below from my Python project:
class PhoneBookApplication: def __init__(self): self.__phonebook = PhoneBook() self.__filehandler = FileHandler("phonebook.txt")I notice that
PhoneBook()is created without arguments, whileFileHandler("phonebook.txt")requires a filename argument.Why is there a difference? Why doesn’t
PhoneBookneed an argument in its constructor?
✅ Answer:
The difference is caused by how the two classes are designed, not by how they are used.
1.
PhoneBook()requires no argumentsThe constructor of
PhoneBookis defined as:class PhoneBook: def __init__(self): self.__persons = {}It takes only
self, which Python supplies automatically.
No external data is required to create a phone book—it simply starts empty.✔ The class can initialize itself internally
✔ No filename, settings, or input is needed
✔ Therefore, you call it asPhoneBook()with no arguments
2.
FileHandler("phonebook.txt")must receive an argumentThe constructor is defined as:
class FileHandler: def __init__(self, filename): self.__filename = filenameThis class cannot operate without knowing which file to read.
Thefilenameargument is required so the object knows:- which file to open
- where to load initial contact data from
If you try to create it without the filename:
FileHandler()Python will raise an error:
TypeError: __init__() missing 1 required positional argument: 'filename'
3. Summary
Class Constructor Requires Argument? Reason PhoneBook()__init__(self)❌ No It starts with an empty dictionary, so no external info needed FileHandler("phonebook.txt")__init__(self, filename)✔ Yes It must know which file to read
🟦 Final Explanation
You only pass arguments to a class when its constructor is designed to accept them.
FileHandlerrequires configuration (a filename);PhoneBookdoes not.
-
AuthorPosts
- You must be logged in to reply to this topic.
