While we are free to bind various properties to an instance, in the real world, an instance of a type should have properties of the same name. For example, what if the person class should have the name, gender, and birth properties when it is created?
When defining the person class, you can add a special __init__ () method to the person class, and when the instance is created, the __init__ () method is automatically called, and we can then unify the following properties for each instance:
class Person (object): def __init__ (self, name, gender, birth): = name = gender = Birth
The first argument of the __init__ () method must be self (or another name, but it is recommended to use idioms), and subsequent arguments can be freely specified, and there is no difference between defining a function.
Accordingly, when you create an instance, you must provide parameters other than self:
Xiaoming = person ('Xiao Ming'Male'1991-1-1 '= person (' Xiao Hong ' Female ' '1992-2-2')
With the __init__ () method, each person instance is created with 3 attributes of name, gender, and birth, and is given a different property value, and the Access property uses the. Operator:
Print Xiaoming.name # output ' Xiao Ming ' Print Xiaohong.birth # output ' 1992-2-2 '
It is important to note that the beginner definition __init__ () method often forgets the self parameter:
>>>classPerson (object): ...def __init__(name, gender, birth): ...Pass... >>> xiaoming = Person ('Xiao Ming','Male','1990-1-1') Traceback (most recent): File"<stdin>", Line 1,inch<module>TypeError:__init__() takes exactly 3 arguments (4 given)
This can cause the creation to fail or run abnormally because the first parameter, name, is passed to the instance's reference by the Python interpreter, causing the entire method's call parameter position to be completely out of alignment.
Example:
The __init__ method that defines the person class, in addition to accepting the name, gender, and birth, accepts any keyword arguments and assigns them all as attributes to the instance.
classPerson (object):def __init__(self,name,gender,birth,**kw): Self.name=name Self.gender=Gender Self.birth=Birth self.kw=kwxiaoming= Person ('Xiao Ming','Male','1990-1-1', job='Student')PrintXiaoming.namePrintXiaoming.kw
Results:
Xiao ming{'job'Student'}
Initializing instance properties in Python