Python object-oriented-method

Source: Internet
Author: User
Tags instance method

Instance method

The private properties of an instance are the __ attributes that begin 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    def get_name(self):        returnself.__name

get_name(self)is an instance method, and its first parameter is self . __init__(self, name)can also be seen as a special instance of the method.

The invocation instance method must be called on the instance:

= Person('Bob')print p1.get_name()  # self不需要显式传入# => 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.

Example

Please Person add a private property to the class __score , represent the score, and then add an instance method get_grade() that can be returned according to __score the value, A-优秀 B-及格 C-不及格 three gears.

Note get_grade() is the instance method, and the first parameter is a self .

Reference code:

classPerson (Object):def __init__( Self, name, score): Self. __name=Name Self. __score=ScoredefGet_grade ( Self):if  Self. __score>=  the:return ' A '        if  Self. __score>=  -:return ' B '        return ' C 'P1=Person (' Bob ', -) P2=Person (' Alice ', $) P3=Person (' Tim ', -)PrintP1.get_grade ()PrintP2.get_grade ()PrintP3.get_grade ()
Method = Property

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

class Person(object):    def__init__(self, name, score):        self= name        self= score    def get_grade(self):        return'A'= Person('Bob'90)print p1.get_grade# => <bound method Person.get_grade of <__main__.Person object at 0x109e58510>>print p1.get_grade()# => A

That is, p1.get_grade a function object is returned, but the function is a function bound to an instance, which is the p1.get_grade() method call.

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

ImportTypesdefFn_get_grade ( Self):if  Self. Score>=  the:return ' A '    if  Self. Score>=  -:return ' B '    return ' C 'classPerson (Object):def __init__( Self, name, score): Self. Name=Name Self. Score=Scorep1=Person (' Bob ', -) P1.get_grade=Types. Methodtype (Fn_get_grade, p1, person)PrintP1.get_grade ()# = AP2=Person (' Alice ', $)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 common, and it is class more intuitive to define it directly in.

Example

Because a property can be a normal value object, such as, and str int so on, it can also be a method, or it can be a function,

class Person(object):    def__init__(self, name, score):        self= name        self= score        self=lambda'A'= Person('Bob'90)print p1.get_gradeprint p1.get_grade()

The function lambda self.get_grade call does not need to be passed self in, but the method call needs to be passed in, which is different from the binding method self .

Class method

Similar to attributes, methods are also divided into instance methods and class methods.

classall defined in is an instance method, and the first parameter of an instance method self is the instance itself.

To class define a class method in, you need to write this:

class Person(object):    =0    @classmethod    def how_many(cls):        return cls.count    def__init__(self, name):        self= name        =+1print= Person('Bob')print Person.how_many()

By marking one @classmethod , the method binds to the Person class, not to an instance of the class. The first parameter of the class method is passed into the class itself, usually named after cls the parameter name, which is cls.count actually equivalent Person.count .

Because it is called on the class, not on the instance, the class method cannot get any instance variables, only the reference to the class is obtained.

Example

If you change the class property count __count to a private property, the external cannot read __score , but can be obtained through a class method, write the class method to get the __count value.

Note that class methods need to be added@classmethod

Reference code:

class Person(object):    =0    @classmethod    def how_many(cls):        return cls.__count    def__init__(self, name):        self= name        =+1print= Person('Bob')print Person.how_many()

Python object-oriented-method

Related Article

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.