-3

I am able to understand what constructors are. But why can't python take initializer lists like c++?

class test:
     def __init__(self, arg1, arg2, arg3):
         self.arg1 = arg1
         self.arg2 = arg2
         self.arg3 = arg3

how will those arguments ever be set without being so manual?

Thanks.

  • 2
    Can a human have time to enter the desired arguments to any other function/method? – Lev Levitsky Feb 12 '13 at 09:35
  • http://stackoverflow.com/questions/625083/python-init-and-self-what-do-they-do -- just to be sure that you *"understand what constructors are"* – root Feb 12 '13 at 09:37
  • 1
    Please don't make such radical changes to a question. Open up a new question instead. – nvoigt Sep 05 '16 at 13:52

4 Answers4

1
test1 = test(1, 2, 3)

A constructor is just like any old function, and you pass arguments to it.

Volatility
  • 31,232
  • 10
  • 80
  • 89
0

Constructor is called once the object is created, not once it is called:

t = test (arg1, arg2, arg3)
Mikhail Vladimirov
  • 13,572
  • 1
  • 38
  • 40
0

Simple - when you instantiate the class later on:

a = test(arg1, arg2, arg3)

a is now a test class, with the 3 arguments set when you initialised it.

TyrantWave
  • 4,583
  • 2
  • 22
  • 25
  • 1
    @CasparWylie you can't have more than one constructor. – Volatility Feb 12 '13 at 09:38
  • The `__init__` is called when you initialise the object - you can't have more than one `__init__` by definition. – TyrantWave Feb 12 '13 at 09:40
  • Those arguments probably have default values (Or will be `None` if not set). `def __init__(self, arg1=2, arg2=3)` will default `arg1,2` to `2,3` respectively if you don't manually set them. – TyrantWave Feb 12 '13 at 09:44
  • And what is the definition of Page1/2/3? – TyrantWave Feb 12 '13 at 09:48
  • ok, here is the whlre script: http://pastebin.com/fC1sxr18 thanks for all the help –  Feb 12 '13 at 09:50
  • Page1/2/3 don't need any specific arguments - the code passes `self` (The main tk.Frame object) as the sole argument. To clarify - `*args` is any positional arguments you'd pass (`Page1(1, 2, 3) -> *args is (1, 2, 3)`), and `**kwargs` is any named arguments (`Page2(b=2, c=3) -> **kwargs is a dict {'b':2, 'c':3}`) – TyrantWave Feb 12 '13 at 09:56
0

The intention behind this is to directly initialize some variables passed to the constructor. The constructor is, as written several times before, called:

t = test(arg1, arg2, arg3)

You have then for the passed parameters defined values in your class.

t0mt0m72
  • 150
  • 5