类中不同方法能否有不同参数?如何为用户类可选添加年龄属性?
1. Technical Question: Can different methods in a class have different parameters?
Absolutely yes! There’s no rule that forces all methods in a class to share the same parameter list. Each method exists to serve a specific purpose, so their parameters should be tailored to what that method needs to do.
For example, a User class might have a login method that requires username and password, and a send_message method that takes recipient and content—these two methods clearly have different parameters, and that’s totally normal and encouraged for clean, functional code.
2. Implementation Suggestions for Your User Class & Age Requirement
First, let’s fix the obvious bugs in your existing code:
- In the
__init__method, you tried to assignnametoself.name, but the parameter you received isuser_name—so it should beself.name = user_name. - There’s a typo:
self.mun_idshould beself.num_idto match the parameternum_id.
Now, for your requirement (adding an age attribute in a separate method, with some users not having an age), here’s a clean, Pythonic implementation:
class User: """A class to save info about every user""" def __init__(self, user_name, num_id): self.name = user_name self.num_id = num_id self.age = None # Initialize age as None for users without age data def set_age(self, age): """Independent method to set the user's age""" self.age = age # Usage examples user1 = User("martin", "1") print(user1.name) # Output: martin print(user1.age) # Output: None (no age set yet) # Set age later using the dedicated method user1.set_age(28) print(user1.age) # Output: 28 # Another user who might never have an age set user2 = User("lisa", "3") print(user2.age) # Output: None
Why this works:
- Initializing
self.age = Nonemakes it clear that the user doesn’t have an age value yet, instead of leaving the attribute undefined (which could cause errors later). - Renaming the method to
set_agefollows Python’s naming conventions (verbs for methods that modify state), making your code more readable for other developers.
If you also want the option to set age when creating a user, you can modify the __init__ method to accept an optional age parameter while keeping the set_age method:
class User: """A class to save info about every user""" def __init__(self, user_name, num_id, age=None): self.name = user_name self.num_id = num_id self.age = age def set_age(self, age): """Independent method to set or update the user's age""" self.age = age # Usage example with age provided upfront user3 = User("bob", "4", 35) print(user3.age) # Output: 35
内容的提问来源于stack exchange,提问作者Weed Cookie

