Advanced python tris (based object-oriented programming) [3-1 python create an instance of a class and]

python creates an instance of a class and

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 the Person () 
Xiaohong = the Person ()

task

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

. 1  class the Person (Object):
 2      Pass 
. 3  
. 4 Xiaoming = the Person ()
 . 5 Xiaohong = the Person ()
 . 6  
. 7  Print Xiaoming
 . 8  Print Xiaohong
 . 9  Print Xiaoming == Xiaohong

 

 

create an instance attributes in python

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.

How to make each instance has its own different 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:

. 1 Xiaoming = the Person ()
 2 xiaoming.name = ' Xiao Ming ' 
. 3 xiaoming.gender = ' for a Man ' 
. 4 xiaoming.birth = ' 1990-1-1 '

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

1 xiaohong = Person()
2 xiaohong.name = 'Xiao Hong'
3 xiaohong.school = 'No. 1 High School'
4 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.

 1 class Person(object):
 2     pass
 3 
 4 p1 = Person()
 5 p1.name = 'Bart'
 6 
 7 p2 = Person()
 8 p2.name = 'Adam'
 9 
10 p3 = Person()
11 p3.name = 'Lisa'
12 
13 L1 = [p1, p2, p3]
14 L2 = sorted(L1,lambda x,y:cmp(x.name,y.name))
15 
16 print L2[0].name
17 print L2[1].name
18 print L2[2].name

 

initializing an instance attribute python

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, __ init __ () method is called automatically, we can here each instance unified add the following attributes:

1 class Person(object):
2     def __init__(self, name, gender, birth):
3         self.name = name
4         self.gender = gender
5         self.birth = birth

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

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

. 1 Xiaoming the Person = ( ' Xiao Ming ' , ' for a Man ' , ' 1991-1-1 ' )
 2 Xiaohong the Person = ( ' Xiao Hong ' , ' for Woman ' , ' 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:

Print xiaoming.name
 # output 'Xiao Ming' 
Print xiaohong.birth
 # output '1992-2-2'

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.

 1 class Person(object):
 2     def __init__(self,name,gender,birth,**kw):
 3         self.name = name
 4         self.gender = gender
 5         self.birth = birth
 6         for k,v in kw.iteritems():
 7             setattr(self,k,v)
 8 
 9 xiaoming = Person('Xiao Ming', 'Male', '1990-1-1', job='Student')
10 
11 print xiaoming.name
12 print xiaoming.job

python access restrictions

We can give an example of binding a lot of property, some property if you do not want to be accessible to the outside how to do?

Python control of property rights is achieved by property name, if an external access to the property by the beginning of the double underscore (__), the property can not be . Look at an example:

 1 class Person(object):
 2     def __init__(self, name):
 3         self.name = name
 4         self._title = 'Mr'
 5         self.__job = 'Student'
 6 p = Person('Bob')
 7 print p.name
 8 # => Bob
 9 print p._title
10 # => Mr
11 print p.__job
12 # => Error
13 Traceback (most recent call last):
14   File "<stdin>", line 1, in <module>
15 AttributeError: 'Person' object has no attribute '__job'

Visible only to double-underlined at the beginning of "__job" can not be directly accessed externally.

However, if a property is defined to "__xxx__" form, that it can be accessed externally, to "__xxx__" defined attributes are called special attributes Python's class, there are many predefined special properties may be used, usually we do not use the common property "__xxx__" definition.

To attribute a single leading underscore "_xxx" although you can also access the external, but, by convention, they should not be external access.

task

Please add to the __init__ method Person class name and score parameters, and the score is bound to the __score properties to see whether the external access to.

 

1 class Person(object):
2     def __init__(self, name, score):
3         self.name = name
4         self.__score = score
5 
6 p = Person('Bob', 59)
7 
8 print p.name
9 print p.__score

 

Guess you like

Origin www.cnblogs.com/ucasljq/p/11622511.html