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.
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.
The __init__ method uses the keyword self to assign the values passed as arguments to the object attributes self. breed and self. eyeColor .
__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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With