Python initializes instance attributes

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.