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 personclass 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): self.name = name Self.gender = Gender Self.birth = 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 ') Xiaohong = 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:
>>> class Person (object): ... def __init__ (name, gender, birth): ... Pass ... >>> xiaoming = person (' Xiao Ming ', ' Male ', ' 1990-1-1 ') Traceback (most recent call last): File "<st Din> ", line 1, in <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.
Task
Define the __init__ method of the person class to accept any keyword arguments in addition to the name, gender , and birth , and assign them all as attributes to the instance.
-
- ? What's going on?
-
To define keyword parameters, use **kw;
In addition to setting a property directly using self.name = ' xxx ' , you can also set properties by setattr (self, ' name ', ' xxx ') .
Reference code:
class Person (object): def __init__ (self, name, gender, birth, **kw): self.name = name Self.gender = gender< C3/>self.birth = Birth for K, V in Kw.iteritems (): setattr (self, k, v) xiaoming = person (' Xiao Ming ', ' Male ', ' 1990 -1-1 ', job= ' Student ') print Xiaoming.nameprint xiaoming.job
Python Initialization Instance Properties