[3-1] Advanced Python classes and instances | define and create an instance of the class / create an instance of property / attribute instance initialization

1. Define and create an instance of the class

In Python, class by class defined keywords. In Person, for example, a Person class defined as follows:

 class Person(object):
     pass

In accordance with the Python programming practice, class names begin with a capital letter, followed by (object), which represents the class is inherited from the class down. Class inheritance will explain in a later chapter, now we just need to simply inherit from the object class.

With the definition of the Person class, you can create a specific example xiaoming, xiaohong and so on. Create an instance of the class name + (), a function call to create a similar form:

xiaoming = Person()
xiaohong = Person()

task:

Please practice the definition of the Person class, and create two instances, print instance, and then compare the two instances are equal.

CODE:

class Person(object):
    pass

xiaoming = Person()
xiaohong = Person()

print xiaoming
print xiaohong
print xiaoming == xiaohong

Here Insert Picture Description

2, create an instance property

Although you can create an instance xiaoming, xiaohong by Person class, etc., but these instances fancy addition to different addresses, but no other difference.
In the real world, the distinction between xiaoming, xiaohong to rely on their own name, gender, birth date and other attributes.

Because Python is a dynamic language, for each instance, it can be directly assigned to their properties, for example, to xiaoming this instance plus name, gender and birth attributes:

xiaoming = Person()
xiaoming.name = 'Xiao Ming'
xiaoming.gender = 'Male'
xiaoming.birth = '1990-1-1'

Xiaohong to add attributes and not necessarily the same as xiaoming:

xiaohong = Person()
xiaohong.name = 'Xiao Hong'
xiaohong.school = 'No. 1 High School'
xiaohong.grade = 2

Examples of attributes may operate the same as normal variables:

xiaohong.grade = xiaohong.grade + 1

task:

Create a list that contains two instances of the Person class and assignment to name two examples, then follow the name order.

CODE:

class Person(object):
    pass

p1 = Person()
p1.name = 'Bart'

p2 = Person()
p2.name = 'Adam'

p3 = Person()
p3.name = 'Lisa'

L1 = [p1, p2, p3]
L2 = sorted(L1, lambda p1, p2: cmp(p1.name, p2.name))

print L2[0].name
print L2[1].name
print L2[2].name


3, initializes instance attributes

While we are free to give an example of binding a variety of attributes, however, the real world, an example of one type of property should have the same name. For example, Person class should just have name, gender and birth attributes when it is created, how do?

When defining the Person class, you can add a special Person class __init __ () method when creating instances, the init () method is called automatically, we can here each instance unified add the following attributes:

class Person(object):
    def __init__(self, name, gender, birth):
        self.name = name
        self.gender = gender
        self.birth = birth

init The first parameter () method must be self (you can also use another name, but it is recommended to use idioms), the follow-up parameters can be freely specified and defined functions without any distinction.

Accordingly, you create an instance, it is necessary to provide the parameters other than self:

xiaoming = Person('Xiao Ming', 'Male', '1991-1-1')
xiaohong = Person('Xiao Hong', 'Female', '1992-2-2')

With __init __ () method, when creating each Person instance, will have a name, gender and birth these three properties, and are assigned different attribute values, using an operator access properties:
(a point)

print xiaoming.name
# 输出 'Xiao Ming'
print xiaohong.birth
# 输出 '1992-2-2'

Pay special attention to that, beginners define __init __ () method often forget the self argument:

>>> class Person(object):
...     def __init__(name, gender, birth):
...         pass
... 
>>> xiaoming = Person('Xiao Ming', 'Male', '1990-1-1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() takes exactly 3 arguments (4 given)

This results in the creation or failure is not functioning properly, because the first parameter name was introduced to the Python interpreter cited examples of leading position of the entire method call parameters of all the no.

task:

Please __init__ method defines the Person class, in addition to accept the name, gender and birth, but also to accept any keyword arguments, and put them all as attributes assigned to the instance.

CODE:

To define the keyword parameters, ** kw;

In addition to directly self.name = 'xxx' set an attribute, but also by setattr (self, 'name', 'xxx') set properties.

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.name
print xiaoming.job
Published 20 original articles · won praise 0 · Views 395

Guess you like

Origin blog.csdn.net/yipyuenkay/article/details/104492039