Python initializes instance attributes
Although we can freely bind various attributes to an instance, in the real world, a type of instance should have attributes with the same name. For example,Person classYou should haveName, genderAndBirthAttribute. What should I do?
When defining the Person class, you can add a special_ Init __()Method. When an instance is created,_ Init __()When the method is called automatically, we can add the following attributes to each instance:
class Person(object): def __init__(self, name, gender, birth): self.name = name self.gender = gender self.birth = birth
_ Init __()The first parameter of the method must beSelf(You can also use other names, but we recommend that you use them in Regular usage). Subsequent parameters can be specified as needed, and there is no difference between them and the definition function.
When creating an instance, you mustSelfOther parameters:
xiaoming = Person('Xiao Ming', 'Male', '1991-1-1')xiaohong = Person('Xiao Hong', 'Female', '1992-2-2')
With_ Init __()Method, each Person instance will haveName, genderAndBirthThese three attributes are assigned different attribute values. The access attribute uses the. OPERATOR:
Print xiaoming. name # output 'xiao ming' print xiaohong. birth # output '2017-2-2'
Note that beginners define_ Init __()Methods often forget 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 "
", line 1, in
TypeError: __init__() takes exactly 3 arguments (4 given)
This will cause the creation to fail or the operation to be abnormal, because the first parameter name is passed into the instance reference by the Python interpreter, so that the call parameter location of the entire method is not correct.
Task
Please definePersonThe _ init _ method of the class, except for acceptingName, genderAndBirthYou can also accept any keyword parameters and assign them to the instance as attributes.
-
? No, what should I do?
-
To define a keyword parameter, use** Kw;
In additionSelf. name = 'xxx'In addition to setting an attribute, you can also useSetattr (self, 'name', 'xxx ')Set Properties.
Reference code:
class Person(object): def __init__(self, name, gender, birth, **kw): self.name = name self.gender = gender 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