-1

I want to add the age for users in a different method but some users might not have an age argument

class User:
    """a class to save info about every user """

    def __init__(self, user_name, num_id):
        self.name = name
        self.mun_id = num_id

    def age(self, age):
        self.age = age

user1 = User("martin", "1")
print (user1.name)
Anwarvic
  • 12,156
  • 4
  • 49
  • 69
Weed Cookie
  • 579
  • 1
  • 3
  • 11
  • Welcome to SO. Please state clearly what is your question, what exactly it is that you are trying to achieve and what trouble you are finding. It is not very clear right now what is the problem you are facing. In any case, you have an `age` method in `User` and then you do `self.age = age`, which will replace that `age` method with the argument you pass. – jdehesa Aug 19 '19 at 10:28
  • 1
    Possible duplicate of [How can you set class attributes from variable arguments (kwargs) in python](https://stackoverflow.com/questions/8187082/how-can-you-set-class-attributes-from-variable-arguments-kwargs-in-python) – Alex Aug 19 '19 at 10:29

2 Answers2

0

define age = None like below and this optional argument should be the last one:

def age(self, age = None):
SM Abu Taher Asif
  • 2,221
  • 1
  • 12
  • 14
0

Yes you can set user age separately. Example below:

user1.age(20)
print (user1.age)
#20 will print
Subhrajyoti Das
  • 2,685
  • 3
  • 21
  • 36