Python interview - Constructor

Python中的constructor就是构造器,简单来说就是class类中的__init__(self)方法。


class FileInfo(UserDict):
    "store file metadata"              1
    def __init__(self, filename=None): 2 3 4



1. 类中可以有这样形式的string。 

Classes can (and should) have doc strings too, just like modules and functions.


2. 当一个实例被创建,__init__会立刻被调用。我们可以说python中的构造器constructor就是__init__方法。但是,有些不准确。因为当__init__被调用的时候,这个对象早早就被构造了,你早就有了合理的reference指向新实例。

__init__ is called immediately after an instance of the class is created. It would be tempting but incorrect to call this the constructor of the class. It's tempting, because it looks like a constructor (by convention, __init__ is the first method defined for the class), acts like one (it's the first piece of code executed in a newly created instance of the class), and even sounds like one (“init” certainly suggests a constructor-ish nature). Incorrect, because the object has already been constructed by the time __init__ is called, and you already have a valid reference to the new instance of the class. But __init__ is the closest thing you're going to get to a constructor in Python, and it fills much the same role.


3. 每一个类方法的第一个参数,都指向类的当前实例,也就是self关键词的含义。在__init__方法中,self指向新创建的对象,在其他方法中,self指向被调用的方法。当定义方法的时候,需要用上self关键词,但是调用的时候不需要,python编译的时候会自动帮你添加上。

The first argument of every class method, including __init__, is always a reference to the current instance of the class. By convention, this argument is always named self. In the__init__ method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called. Although you need to specify self explicitly when defining the method, you do not specify it when calling the method; Python will add it for you automatically.


4. __init__方法可以传入无尽的参数,也可以传入functions,参数可以有default的值。在case中,filename的默认值就是None。

__init__ methods can take any number of arguments, and just like functions, the arguments can be defined with default values, making them optional to the caller. In this case,filename has a default value of None, which is the Python null value.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值