Python class methods

Source: Internet
Author: User

First, class

Definition of Class 1.1

#1.1.1 No parameter definitionclassTest (object):def __init__(self):Pass    defFunc (self):#class Method        Pass#1.1.2 has a parameter definitionclassFoo (object):def __init__(self,name,age): Self.name= Name#Class PropertiesSelf.age = Age

Method of invocation of class 1.2

obj = Test ()
OBJ is now called an object, which is the resulting object after instantiating the test class.
Print (obj)
# <__main__.test Object at 0x00000000024c7ef0> = foo (' King Cannon ', ') # Call the class Shishun, equal to call the __init__ method in the class, call the method and call the function, Just the call is going to pass in self itself parameter print(obj1.age) # object property Call
# 23

1.3 Object Method Invocation

classStudent ():#Defining Classes    def __init__(self,name,age): Self.name=name Self.age= AgedefLearn (Self,object):#define class methods, Parameter object, course        Print('%s is learning%s'%(self.name,object)) WDP= Student ('King Cannon', 23)#instantiate the resulting object and assign it to WDP, at which time WDP inherits the methods and properties of the classPrint(WDP.__dict__)#Viewing Object Properties#{' name ': ' King Cannon ', ' age ': +}Wdp.learn ('English')#Call object method, call without parameter self argument#Wang Cannon is learning English.
classStudent ():#Defining Classes    def __init__(self,name,age): Self.name=name Self.age= AgedefLearn (Self,object):#define class methods, Parameter object, course        Print('%s is learning%s'%(self.name,object)) LTG= Student ('Lee Tank', 33)#class is called when the self parameter needs to be passed in, the object does not needStudent.learn (LTG,'History')#This method is the same as the Ltg.learn (' history ') result. #Lee Tank is studying history.
understand that classes call their own methods directly

the non-binding method of class

The non-binding method of Class 1.1 uses

classFoo (object):def __init__(self):Pass@staticmethod#just add a @staticmethod above the method and remove the self parameter from the method    deffunc (content):Print(content)#calledobj =foo () Obj.func ('I'm an object-unbound method')#I'm an object-unbound methodFoo.func ('I am a class-unbound method')#I am a class-unbound method

1.2 Note points for non-binding methods

  A non-binding method, like a normal function, cannot directly invoke its own properties and methods.

#note points for non-binding methodsclassTeacher (object): Addr='Shanghai'    def __init__(self,name,course): Self.name=name Self.course=Course @staticmethod#just add a @staticmethod above the method and remove the self parameter from the method    deffunc ():Print('This is%s'%TEACHER.ADDR)#This is Shanghai        Print('This is a%s teacher'%self.course)#error, because there is no self parameterTeacher_li= Teacher ('Li xx','language') Teacher_li.func ()#this will
A non-binding is just like a normal function, except that it is defined within a class, outside a class

1.3 Summary

# Summary    # 1, the non-binding method class, the province and the object can be called    # 2. A non-binding method can not directly invoke a property or method of the class or object itself

third, class binding method

Use of class 1.1 binding methods

classfoo ():def __init__(self):Pass@classmethoddefGet_instance (CLS):#cls = = Foo        if  notHasattr (CLS,"instance"): Cls.instance=CLS ()returncls.instance#Singleton mode, instancing only onceObj1 =foo.get_instance () obj2=foo.get_instance ()Print(OBJ1,OBJ2)#Two-time instantiation results, stating that only one time is instantiated#--------up and down--------obj_x =foo () obj_y=foo ()Print(obj_x,obj_y)#Two instantiation results are different

1.2 Summary

# Features: Who is bound to whom     it is called, who invokes it as the first parameter in the # bound to the object method: The        function defined in the class, without being decorated by any adorner, The default is to bind to the object's # method that is bound to the class in the function defined in the class, in the case where the         adorner is classmethod decorated, the method is the # of the binding class Note:    class can be used as normal as the object's binding method

Iv. Encapsulation Attribute method

4.1 Methods that look like attributes (are attributes, but internal implementations are methods)

classpeople (object):def __init__(self,name,height,weight): Self.name=name Self.height=Height Self.weight=Weight @propertydefBMI (self):returnSelf.weight/(self.height * * 2) Me= People ('JMZ', 1.75,68)#encapsulate a method as a propertyPrint(ME.BMI)#22.20408163265306Print(Me.bmi ())#report TypeError's mistake.

4.2 Properties can be modified can be deleted (the above method can not be deleted), How to implement ?

classGood ():def __init__(self,name,price): Self.name=name self.__price= Price#Double downline is a class-private property that can only be used within the class itself and cannot be accessed externally@propertydefPrice (self):returnSelf.__price@price. Setter#change properties. Setter    defPrice (self,price): Is_int_price= str (price). Strip (). Replace ('.',"')#Convert to digital        if  notis_int_price.isdigit ():RaiseTypeError ('%s is not a numeric type'%Price ) self.__price=Price @price. deleter#Delete property. deleter    defPrice (self):#del Self.__price        Print('don't let it be deleted, old iron.') Sy= Good ('Yam','1.3')Print(sy.price) Sy.price= 1.4Print(Sy.price)delSy.price

4.3 Summary

Encapsulation Properties Highlights:     1, modify  the @price.setter and delete @price. deleter must be under @property. 

Python class methods

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.