Python Object-oriented

Source: Internet
Author: User

1.Create class properties in Python

A class is a template, whereas an instance is an object created from a class.

A property that is bound on one instance does not affect other instances, but the class itself is an object, and if you bind a property to a class, all instances can access the properties of the class, and the class properties accessed by all instances are the same! That is, instance properties each have each instance owned and independent of each other, and the class attribute has only one copy.

Defining class properties can be defined directly in class:

class Person (object):     ' Earth '    def __init__ (self, name):         = Name

Because class properties are directly bound to classes, access to class properties does not require an instance to be created and can be accessed directly:

Print person.address # = Earth

A property that invokes a class on an instance is also accessible, and all instances have access to the properties of the class to which it belongs:

P1 = person ('Bob'= person ('Alice') Print p1.address # = Earth Print p2.address # = Earth

Because Python is a dynamic language, class properties can be added and modified dynamically:

'  China ' Print p1.address # = ' China ' Print p2.address # = ' China '

Because the class attribute has only one copy, when the address of the person class changes, the class properties accessed by all instances change.

2. How does the class attribute and instance property name conflict in Python?

Modifying a class property causes all of the class properties accessed by the instance to be affected, but what happens if the Class property is modified on an instance variable?

classPerson (object): Address='Earth'    def __init__(self, name): Self.name=Namep1= Person ('Bob') P2= Person ('Alice')Print 'person.address ='+Person.addressp1.address=' China'Print 'p1.address ='+p1.addressPrint 'person.address ='+person.addressPrint 'p2.address ='+ p2.address

The results are as follows:

Person.Address = = = = Earth

We found that after setting the p1.address = ' China ', the P1 access address did become ' China ', but Person.Address and p2.address are still ' earch ', what's going on?

The reason for this is that p1.address = ' China ' does not change the address of the person, but instead binds the instance attribute address to the P1 instance, and for P1, it has an instance attribute address (the value is ' China '), The class person to which it belongs also has a class attribute address, so:

When accessing p1.address, first look for instance properties and return ' China '.

When accessing p2.address, P2 does not have an instance attribute address, but has a class attribute address, and therefore returns ' Earth '.

It can be seen that when instance properties and class attributes have the same name, the instance property has a high precedence, which masks access to the class properties.

When we delete the P1 address instance property, access to P1.address returns the value of the class attribute ' Earth ':

del p1.address Print p1.address # = Earth

As you can see, never modify a class property on an instance, it does not actually modify the class property, but instead binds the instance to an instance property.

3. Define instance methods in Python

The private property of an instance is a property that begins with __ and cannot be accessed externally, what is the use of these attribute definitions?

Although private properties cannot be accessed externally, they can be accessed from within the class. In addition to defining the properties of an instance, you can define the methods of the instance.

An instance is a function defined in a class whose first argument is always self, pointing to the instance itself that invokes the method, and the other arguments are exactly the same as a normal function:

class Person (object):     def __init__ (self, name): Self        . __name = name    def  get_name (self):        return to self.  __name

Get_name (self) is an instance method whose first argument is self. __init__ (self, name) can also be seen as a special instance method.

The invocation instance method must be called on the instance:

P1 = person ('Bob')print p1.get_name ()  # Self does not need to be explicitly passed in  #  = Bob

Within an instance method, all instance properties can be accessed, so that if the external needs access to private properties, which can be obtained through a method call, the form of the data encapsulation can simplify the external invocation in addition to protecting internal data consistency.

Practice:

__score The values of __score return A-excellent, B-pass, C-fail three.
#-*-coding:utf-8-*-classPerson (object):def __init__(self, Name, score): Self.__name=name self.__score=scoredefGet_grade (self):ifSelf.__score>=80:            return "A-Excellent"        elifSelf.__score>=60:            return "B-Pass"        return "C-Inferior lattice"P1= Person ('Bob', 90) P2= Person ('Alice', 65) P3= Person ('Tim', 48)PrintP1.get_grade ()PrintP2.get_grade ()PrintP3.get_grade ()

4. Methods in Python are also attributes

The instance method that we define in class is actually a property, which is actually a function object:

classPerson (object):def __init__(self, Name, score): Self.name=name Self.score=scoredefGet_grade (self):return 'A'P1= Person ('Bob', 90)PrintP1.get_grade#= <bound method Person.get_grade of <__main__. Person object at 0x109e58510>>PrintP1.get_grade ()#= A

In other words, P1.get_grade returns a function object, but this function is a function bound to an instance, and P1.get_grade () is the method call.

Because the method is also a property, it can also be dynamically added to the instance, just need to use types. Methodtype () turns a function into a method:

ImportTypesdefFn_get_grade (self):ifSelf.score >= 80:        return 'A'    ifSelf.score >= 60:        return 'B'    return 'C'classPerson (object):def __init__(self, Name, score): Self.name=name Self.score=Scorep1= Person ('Bob', 90) P1.get_grade=types. Methodtype (Fn_get_grade, p1, person)PrintP1.get_grade ()#= AP2 = person ('Alice', 65)PrintP2.get_grade ()#error:attributeerror: ' Person ' object with no attribute ' Get_grade '
# because the P2 instance is not bound Get_grade

Adding a method to an instance dynamically is not uncommon, and it is more intuitive to define it directly in class.

Python Object-oriented

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.