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.