Python's object-oriented programming approach to learning notes

Source: Internet
Author: User
Classes and instances
A class is associated with an instance: A class is the definition of an object, and an instance is a "real thing," which holds specific information about the objects defined in the class.

The following example shows how to create a class:

Class Mynewobjecttype (Bases):   "Create Mynewobjecttype class"   Class_suite

The keyword is class, followed by a class name. The class code for the class is then defined. This is usually made up of a variety of definitions and declarations. The biggest difference between the modern class and the classic class declaration is that all modern classes must inherit at least one parent class, and the parameter bases can be either one (single-inheritance) or multiple (multiple-inheritance) parent classes for inheritance.

The process of creating an instance is called instantiation, as follows (note: The New keyword is not used):

Myfirstobject = Mynewobjecttype ()

The class name appears as a function call using the function operator (()) that we are familiar with. Then you will usually assign this new instance to a variable. The assignment is not syntactically necessary, but if you do not save the instance to a variable, it is useless and will be reclaimed by the automatic garbage collector, since any references point to this instance. So, all you've just done is allocate a piece of memory for that instance and then release it.

Classes can be both simple and complex, all from your needs. In the simplest case, the class is used only as a namespace (namespace). This means that you keep the data in variables, grouping them by namespace so that they are in the same relationship space-so-called relationships are identified using the standard Python period attribute. For example, you have a class that does not have any properties of its own, using it to provide only a namespace for your data, to have your class have the same attributes as the struct (structure) in C, or, in other words, to share namespaces only as container objects.

Examples are as follows:

Class MyData (object):  passmathobj = MyData () mathobj.x = 4MATHOBJ.Y = 5mathobj.x + mathobj.y9mathobj.x \\* mathobj.y20

Method
In Python, a method is defined in a class definition, but can only be called by an instance. In other words, the final way to invoke a method must be this: (1) Define the class (and method), (2) Create an instance, (3) The last step, call the method with this instance. For example:

Class Mydatawithmethod (object): # defines class  def printfoo (self): # define method    print ' you invoked Printfoo ()! '

Here is the self parameter, which is present in all method declarations. This parameter represents the instance object itself, which is passed to the method by the interpreter when you invoke the method with the instance, so you do not need to pass self in as it is automatically passed in.

For example, if you have a method with two parameters, all your calls only need to pass the second argument.

The following is an instantiation of this class, and the method is called:

> > > MYOBJ = Mydatawithmethod () > > > Myobj.printfoo () you invoked Printfoo ()!

\\_init\\ (), is a special method. In Python, \\init\\ () is not actually a constructor. You have not called "new" to create a new object. (Python doesn't have the keyword "new" at all). Instead, when Python creates an instance, it calls the \\init\\_ () method during instantiation, and when a class is instantiated, it can define additional behavior, such as setting an initial value or running some preliminary diagnostic code--primarily after the instance has been created, before the instantiation call returns to the instance. To perform certain tasks or settings.

Create a class (class definition)

Class Addrbookentry (object):  "Address Book entry class"  def __init__ (self, NM, ph): # define constructor    Self.name = n  M       # set name    self.phone = ph       # set phone    print ' Created instance for: ', Self.name  def updatephone (self, NEWPH):  # definition method    self.phone = newph    print ' Updated phone# for: ', self.name

In the definition of the Addrbookentry class, two methods are defined: \\_init\\ () and Updatephone (). \\init\\ () is invoked when instantiated, that is, when Addrbookentry () is called. You can think of instantiation as an implicit call to \\init\\ () because the argument passed to Addrbookentry () is exactly the same as the parameter received by \\init\\_ () (except for self, which is passed automatically).

Create instance (instantiate)

> > > John = addrbookentry (' John Doe ', ' 408-555-1212 ') # Create an instance for John Doe > > > Jane = addrbookentry (' Jane Doe ', ' 650-555-1212 ') # Create an instance for Jane Doe

This is the instantiation call, which automatically calls \\_init\\ (). Self automatically passes the instance object into \\init\\_ ().

In addition, if no default parameter exists, then the two parameters passed to \\_init\\_ () are required for instantiation.

accessing instance Properties

> > > John> > > John.name> > > Jane.name> > > Jane.phone

Once the instance is created, it is possible to confirm that our instance properties are actually set by \\_init\\_ () during the instantiation process. We can use the interpreter dump instance to see what type of object it is.

Method invocation (through instance)

> > > John.updatephone (' 415-555-1212 ')  # update John Doe's phone > > > John.phone

The Updatephone () method requires a parameter (regardless of self): the new phone number. After Updatephone (), check the instance properties immediately to verify that it is in effect.

method and property summary
directly on the code, there are comments in it

#coding: utf8name = ' yangyanxing ' class Test (): Class Kevin (): var1 = ' I am the inner class ' name = ' Kvein ' gae = ' def ' (self ): Print self.name print ' I am a public method ' self.__fun2 () #可以通过公有就去来调用私有方法, can be changed during the call Def __fun2 (self): print ' I am a private party Act ' @classmethod def fun3 (self): #可以不通过实例来访问这个类方法 print ' # ' *40 print self.name print ' I am a class method ' @staticmethod #静态方 method, which can be accessed without using an instance object, but does not add the self def fun4 (): Print test.name print name #这里的name是全局变量 test.fun3 () print ' I am the static method ' print Test.name #公有属性可以直接方法 without instantiating the object Yang = Test () #实例化一个类interyang = Test.kevin () #实例化一个内部类yang. FUN1 () # The public properties of the method class print Interyang.var1 # Access the properties inside the class Test.fun3 () #访问类方法Test. FUN4 () #coding: Utf8class Test (): var1 = ' public properties of class ' __var2 = ' private property of class ' Def fun (self): self.var2 = ' public Property of object ' # This defines an object's public property Self.__var3 = ' object's private property ' # Here you define a private property of an object VAR4 = The ' local variable ' of the function ' #这里定义了一个函数的局部变量 that the VAR4 is only used inside the function using the Kevin = Test () #实例了一个对象yang = Test () #又实例了另外一个对象print kevin.var1# #print Kevin.__var2 #这里将无法访问kevin. Fun () print Kevin.Var2 #在没有调用fun函数之前是没有var2的 # #print The private property of the Kevin.__var3 object is a # #print yang.var2 #这里因为没有调用yang的fun方法 that cannot be called So I still can't access the var2 in Yang.


Creating subclasses
Subclass by inheritance is a way to create and customize a new type, and the new class will maintain all the attributes of the existing class without altering the definition of the original class. For a new class type, this new subclass can customize the specific functionality that belongs to it only. In addition to the relationship to the parent class or base class, subclasses are no different from the usual classes, and are instantiated as normal classes. Note the following, the parent class is mentioned in the subclass declaration:

Class Empladdrbookentry (addrbookentry):  "Employee Address Book Entry class" # Employee Directory Class  def __init__ (self, NM, ph, ID, EM):    addrbookentry.__init__ (self, NM, ph)    self.empid = id    self.email = em  def updateemail (self, NEWEM):    self.email = newem    print ' Updated e-mail address for: ', self.name

Now we have created the first subclass, Empladdrbookentry. In Python, when a class is derived, subclasses inherit the properties of the base class, so in the above class we define not only the \\_init\\_ (), Updateemail () method, but also empladdrbookentry from Addrbookentry The Updatephone () method is inherited from the

If required, each subclass is best defined by its own constructor, otherwise the constructor of the base class is called. However, if the subclass overrides the constructor of the base class, the constructor of the base class will not be called automatically-so that the constructor of the base class must be explicitly written out to be executed, as we did above, using Addrbookentry.\\_init\\_ () to set the name and phone number. Our subclasses also set two additional instance properties in the following rows of the constructor: Employee ID and e-mail address.

Note that we're going to explicitly pass the self instance object to the base class constructor, because we're not in that instance but we're calling that method in a subclass instance. Because we are not invoking it through an instance, this unbound method call needs to pass an appropriate instance (self) to the method.

Using subclasses

> > > John = Empladdrbookentry (' John Doe ', ' 408-555-1212 ', ' John@spam.doe ') > > > John> > > john.name> > > John.phone> > > John.email> > > John.updatephone (' 415-555-1212 ') > > > J ohn.phone> > > John.updateemail (' john@doe.spam ') > > > John.email
  • 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.