Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to call an init method in self, in an init method?

Recently I realized I needed to add an argument to the init method for a helper class I've got. The helper class deals with alert views so it already has a bunch of arguments in the init, which are looked at, tweaked, and then sent on to the alert view.

Since I'm using the method as it is in various places, I don't want to risk crashing (by missing one of those places and getting an 'unrecognized selector' in the hands of a customer) so I decided to add a second init method.

I.e.

- (id)initWithA:B:C:D:

and

- (id)initWithA:B:C:foo:D:

Right now I've simply copy pasted the first one's implementation into the foo: one, but ideally what would be nice is making the first call the second, i.e.

- (id)initWithA:a B:b C:c D:d
{
    return [self initWithA:a B:b C:c foo:nil D:d];
}

but I'm not sure if this is acceptable or not. Code appears to be working fine.

like image 339
Kalle Avatar asked Aug 16 '10 16:08

Kalle


People also ask

Can you call methods in __ init __?

Calling other methods from the __init__ methodWe can call other methods of the class from the __init__ method by using the self keyword. The above code will print the following output.

What is Self In __ init __ method?

The __init__ method uses the keyword self to assign the values passed as arguments to the object attributes self. breed and self. eyeColor .

Does init always need self?

__init__ does act like a constructor. You'll need to pass "self" to any class functions as the first argument if you want them to behave as non-static methods.

Why Self is used in Init method?

The self in keyword in Python is used to all the instances in a class. By using the self keyword, one can easily access all the instances defined within a class, including its methods and attributes. __init__ is one of the reserved methods in Python. In object oriented programming, it is known as a constructor.


1 Answers

Yes, that is perfectly acceptable and actually quite common.

This is why we have things called a "Designated Initializer". That's the initializer method to which all other initializers get redirected (usually).

like image 184
Dave DeLong Avatar answered Oct 13 '22 08:10

Dave DeLong