黑马程序员——构造方法之init的重写和自定义构造方法

本文详细介绍了Objective-C中构造方法的使用方式,包括初始化方法的重写规则、自定义构造方法的规范及其实现过程。通过具体的代码示例,展示了如何在Person及Student类中实现不同形式的构造方法。

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

1、构造方法的概念:

    是一个用来初始化对象默认值对象方法


2、init方法的重写规则:

- (id)init
{
    if ( self = [super init] )
    { 
        _someThing = 10;  //   如果初始化父类成功则给本对象的成员变量赋值
    }
    
    // 返回已经初始化完毕的本对象
    return self;
}

3、自定义构造方法:

Person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject
@property NSString *name;
@property int age;

/*
 自定义构造方法的规范
 1.一定是对象方法,一定以 "-" 开头
 2.返回值一般是id类型
 3.方法名一般以initWith开头
*/

- (id)initWithName:(NSString *)name;

- (id)initWithAge:(int)age;

- (id)initWithName:(NSString *)name andAge:(int)age;

@end

Person.m

#import "Person.h"

@implementation Person

- (id)initWithName:(NSString *)name
{
    if ( self = [super init] )
    {
        _name = name;
    }
    
    return self;
}

- (id)initWithAge:(int)age
{
    if ( self = [super init] )
    {
        _age = age;
    }
    return self;
}

- (id)initWithName:(NSString *)name andAge:(int)age
{
    if ( self = [super init] )
    {
        _name = name;
        _age = age;
    }
    return self;
}

@end

Student.h

#import "Person.h"

@interface Student : Person
@property int no;

- (id)initWithNo:(int)no;

- (id)initWithName:(NSString *)name andAge:(int)age andNo:(int)no;

@end

Student.m

#import "Student.h"

@implementation Student
- (id)initWithNo:(int)no
{
    if ( self = [super init] )
    {
        _no = no;
    }
    return self;
}

// 父类的属性交给父类方法去处理,子类方法处理子类自己的属性
- (id)initWithName:(NSString *)name andAge:(int)age andNo:(int)no
{
    // 将name、age传递到父类方法中进行初始化
    if ( self = [super initWithName:name andAge:age])
    {
        _no = no;
    }
    
    return self;
}

@end

main.m

#import <Foundation/Foundation.h>
#import "Person.h"
#import "Student.h"

int main()
{
    Student *p = [[Student alloc] initWithName:@"Jim" andAge:29 andNo:10];
    
    return 0;
}

在Python里,`__init__`方法属于构造方法的一种具体形式,不过通常意义上的构造方法涵盖的范围更广,包含`__new__`方法等,下面是二者的区别: ### 功能层面 - **`__init__`方法**:是初始化函数,其作用为把变量绑定到实例,更新实例的`__dict__`字典。比如在`class Computer`里,`__init__`方法将`open``run`参数绑定到实例上 [^1][^2]。 ```python class Computer(): cup = 'CPU' memery = '内存' Display_card = '显卡' Drive = '驱动器' # 构造方法 def __init__(self, open, run): self.open = open self.run = run print(f"{self.open, self.run}") ``` - **构造方法**:从广义来讲,构造方法负责对象的创建与初始化。`__new__`是构造方法,它先于`__init__`执行,用于定制类的创建过程;`__init__`也可看作构造方法,负责对象的初始化 [^1][^3]。 ### 执行顺序层面 - **`__init__`方法**:在`__new__`方法之后执行。`__init__`的第一个参数`self`是`__new__`的返回值,也就是类的实例 [^1]。 - **构造方法**:以`__new__`为例,它先执行,返回一个新的实例,之后才会调用`__init__`方法对该实例进行初始化 [^1]。 ### 使用方式层面 - **`__init__`方法**:在实例化对象时自动调用,不能手动调用。如`computer1 = Computer('kaiji', 'yunxing')`,实例化`Computer`类时,`__init__`方法自动执行 [^2]。 - **构造方法**:像`__new__`方法,一般在需要定制类的创建过程时使用,要手动重写该方法;而`__init__`作为构造方法的一种,使用时会自动调用 [^3]。 ### 代码示例差异 - **`__init__`方法**: ```python class Example: def __init__(self, value): self.value = value print(f"Initialized with value: {self.value}") obj = Example(10) ``` - **构造方法(以`__new__`为例)**: ```python class CustomExample: def __new__(cls, value): print("Creating a new instance...") instance = super().__new__(cls) return instance def __init__(self, value): self.value = value print(f"Initialized with value: {self.value}") obj = CustomExample(20) ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值