-1

The code bellow in c++ is working, Its possible to make this works with python without using Users().Users(23, "bell") but like c++ Users(23, "bell") see my code bellow

#include <iostream>
using namespace std;


class Users
{
public:
    int age;
    string name;

public:
    Users()
    {
        // init default 
        age = 90;
        name = "john";

    }

    Users(int iage, string iname)
    {
        age = iage;
        name = iname;
    }
};


int main()
{
    Users User;
    User.age = 2;
    User.name = "l";

    Users(23, "bell");
    return 0;
}

''

class Users:
    age = None
    name = None 

    def __init__(self):
        self.age = 90
        self.name = "john"

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

User = Users()
User.age = 2
User.name = "l"
11
  • .... that's what the __init__ function's there for. __init__ is python's constructor. just add the arguments there and remove your User method, it has no special meaning in Python. Commented Jul 11, 2018 at 12:06
  • Have you read the basic tutorial? Your actual question is unclear but I'm pretty sure you're trying to add arguments to __init__. Commented Jul 11, 2018 at 12:09
  • no i dont want to add arg to init Commented Jul 11, 2018 at 12:10
  • 1
    Yes you do. Function (or constructor) overloading is done with default arguments in python. Commented Jul 11, 2018 at 12:12
  • 2
    Please don't edit the solution into your question. Solutions don't belong in the question, they should be posted as answers. Commented Jul 11, 2018 at 12:22

1 Answer 1

2

Use default arguments to provide values when you don't want to pass a default value explicitly.

class User:  # singular noun
    def __init__(self, age=90, name="john"):
        self.age = age
        self.name = name

user1 = User()            # user.age == 90, user.name == "john"
user2 = User(2, "l")      # user.age == 2, user.name == "l"
user3 = User(40)          # user.age == 40, user.name == "john"
user4 = User(name="bob")  # user.age == 90, user.name == "john"

Since the unspecified arguments are replaced by defaults in strict left-to-right order, the last example shows the use of a keyword argument to set the name explicitly while using the default age.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.