Python Object-oriented members

Source: Internet
Author: User
Tags instance method

I. Overview

In the previous article, "Python Object-oriented OOP" introduces the basic introductory part of Python object-oriented, mentions the definition of class, the use of class, the three major characteristics of classes, the difference between the classical class, the new class in the search, and so on, with the previous foundation, this article then describes the object-oriented class members; The members in the class are divided into the following sections:

#类成员

  #Field(properties):
normal field  belongs to the object,Save in Object,access only through objects
static fields  belongs to class,Save(a copy)in the class(Field properties shared by all objects),can be either class access or object access at execution time
#Method:
The normal method is saved in the class, also called the instance method, first creates the object,object indirect access to common methods,class can also access,need to pass objectsself==>Object
static methods by adding@staticmethodadorner becomes static method,Save in class; Selfcan save,This can be called directly from the class,encapsulation of functions similar to modules
class method by adding@classmethodSave in class,called directly by the class, CLS ==>Current Class
#Properties (attributes):
Define by Method ,called as field property


Second, class field properties

Class foo:public = "IsClass" #静态字段 def __init__ (self,arg): Self.name = "A" # #普通字段 Self.arg = arg # #普通字段 def bar (self): print (self.name,self.arg) obj = Foo ("Hello") Obj.bar () print (obj.public) print (Foo . public)

Operation Result:

A Hello
IsClass

IsClass


Description: A property defined in a Class (field) We call a static field, it is not an object, belongs to a class, the advantage is that no matter how many objects are created, it only retains one copy in memory; self.xxx = xxxx This, because self represents the object itself, so saved in the object, belongs to the object, called the normal field, How many objects are instantiated, and how many copies are kept in memory. Static fields and normal fields, which can be called by instantiated objects. A static field can also be called by a class in addition to objects that can be called. The class cannot call the object's normal field, however, because it belongs to the object.


Iii. methods in the class

Class methods are divided into ordinary methods, class methods, static methods three of the following we separately to illustrate:

1. Common method (Example method)

class foo:    public =  "IsClass"   #  static fields      def __init__ (self,name,age):        self.name =  name     # #普通字段         self.age =  age       # #普通字段     def bar (self,arg):         print (Self.name, self.age,argobj = foo ()        #实例化出obj对象obj. Bar (666)             # Call Bar Normal method Foo.bar (obj,666)          #通过Foo类传入obj对象调用bar方法 
via obj object
Operation Result:

San 18 666
San 18 666


Description: For the common method, save in the class, the instance object can be called directly (parameters need to pass the parameter), the class can call the method to pass in the object, and the required parameters, the same effect. Therefore, for the normal method, the instance object can be called, the class can also be called, but the premise is to instantiate the object, either directly or through the class call to pass the instance object.


2. Static method

class foo:    def __init__ (self,name,age):         self.name = name        self.age = age     def showinfo (self):         print ( Self.name,self.age)      @staticmethod        #通过 @staticmethod   Converting methods to static methods     def stac ():         # static method when self is not required, add self does not mean object         print ("Static")       @staticmethod     def stac2 (A1,A2):         print (A1,A2)         obj = foo ("San")         #实例化出对象objobj. Showinfo ()              #obj对象调用showinfo普通方法obj. Stac ()                # Obj calls class static method Stacobj.stac2 (           #) Obj calls a class that needs to pass arguments static method Stac2foo.stac ()                  #Foo类直接调用静态方法stacFoo. STAC2 (           #) The Foo class directly calls the class static method that needs to pass the argument Stac2

Operation Result:

650) this.width=650; "title=" static method. png "alt=" 5018cc47687c2addef56a04913b8adc3.png-wh_ "src=" https://s4.51cto.com/ Oss/201711/18/5018cc47687c2addef56a04913b8adc3.png-wh_500x0-wm_3-wmp_4-s_2797828922.png "/>


Description: The static method is saved in the class by adding the @staticmethod adorner to the method, and the static method does not need to pass in the self parameter, even if it is passed in as the normal method does not refer to the object itself. And just a normal shape parameter. A class static method object can be called, but is primarily called to a class. Equivalent to the module's encapsulation of functions.


3. Class methods

Foo: (, Name,age):. Name = name. Age = Age Showinfo (): (. name,.age) Classmd (, Arg): () (, arg) obj = Foo (,) Obj.showinfo () Foo.classmd () Obj.classmd ()

Operation Result:

650) this.width=650; "Title=" class method. png "alt=" 52d6680299e98b4bafc8933b32bfc09c.png-wh_ "src=" Https://s5.51cto.com/oss /201711/18/52d6680299e98b4bafc8933b32bfc09c.png-wh_500x0-wm_3-wmp_4-s_2404342322.png "/>


Description: The definition of a class method is saved in the class by adding @classmethod before the method. The default parameter is CLS,CLS, which refers to the class itself, the class is callable, and the object can be called. It is transmitted when the parameter is passed.


The above are the three methods of the class, they are all saved in the class, and the instantiated object can be called.

The common method of the class is the instance method, which is the most common method in the class, which is called by the instance, and the class cannot be called without an instance, and it is required to pass in the instance and parameter (if any) object. method ([parameter]) = = Class. Method (Instance object, [parameter])


A method that runs in a class without running in an instance, we want the method to be available as a class method when it is not running in the instance, mainly for class invocation, the passed-in parameter is a class, and is primarily used to modify the data related to the class. A class can be called directly without an instance. Instances can also be called.


There are often some functions that are related to the class, but static methods are required when the runtime does not require instances and classes to participate. A bit resembles the encapsulation of a module to a function.

So we # if you need to save some values in an object, use the values in the object when performing a function, use the normal method # does not require any values in the object, use a static method, you need to modify the values in the class using the class method.


Iv. attributes in a class

Now we all know that a method in a class is an over object. method ([parameter]) is called, but sometimes for brevity, you want to turn this into a object. Property to get the value, This refers to the attribute @property in the class, which looks at the example:

Class foo (object):     def __init__ (self):         self.name =  "a"             # #普通字段     #obj. Name Get     def bar (self):                   #实例方法  obj.bar () call          print ("bar")      @property                        # property or called attribute    used to perform obj.per get value     def per (self):         return  1     @per .setter                     #设置值  obj.per =  values     def pER (self,val):         print (val)      @per. deleter                     #  Delete value     def per (self):         Print (66666)         obj = foo ()         #实例化objr  = obj.per      # Because the Per method adds @property, the call to print (R) obj.per = 123    # is obtained by Obj.per @per. Setter will pass 123 into Del  obj.per       # @per. deleter Delete function, simulate here, can do any function that you want to do

Operation Result:

650) this.width=650; "title=" Property.png "alt=" Ac407a7406aa74a223a5ae32d73568df.png-wh_ "src=" https:// S1.51cto.com/oss/201711/18/ac407a7406aa74a223a5ae32d73568df.png-wh_500x0-wm_3-wmp_4-s_2852783540.png "/>


Another way to do this:

class foo:    def f1 (self):             #等同于 @property  def f1         return 123                         DEF F2 (self,v):         print (v)     def f3 (self):         print ("del")     per = property (FGET=F1,FSET=F2,FDEL=F3)     #第一个参数默认是fgetobj  = foo ()         #实例化obj对象ret  = obj.f1    print (ret ()) obj.per = 2     #传输值2print (obj.per)   #调用obj. PER == OBJ.F1 () del obj.per     #删除obj. per ==   OBJ.F3 () 

Operation Result:

650) this.width=650; "title=" Property02.png "alt=" 580a80164eb26e8f929f75ef0e0c1932.png-wh_ "src=" https:// S3.51cto.com/oss/201711/18/580a80164eb26e8f929f75ef0e0c1932.png-wh_500x0-wm_3-wmp_4-s_2404413051.png "/>

Summary: You can change a method into a similar property invocation form by using the @property adorner. Make the code look more concise.

The above is a personal summary, if there is a mistake to welcome the exchange.

This article is from the "Learning, learning" blog, please be sure to keep this source http://dyc2005.blog.51cto.com/270872/1982981

Python Object-oriented members

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.