Python-Object-Oriented Programming (Introduction)

Source: Internet
Author: User

I. Classes and Instances

Classes and instances are associated with each other: classes are the definition of objects, while instances are "real objects ". The following example shows how to create a class:

>>> class MyNewObjectType(bases):...     'define MyNewObjectType class'...     class_suite...
The keyword is class, followed by a class Name. Then, it defines the class body code of the class. The class must inherit at least one parent class. The parameter bases can be one (single inheritance) or multiple (Multi-inheritance) parent classes used for inheritance. Object is the mother of all classes ". If your class does not inherit any other parent class, the object will be the default parent class. It is located at the top of all class inheritance structures.

The process of creating an instance is called Instantiation. The process is as follows:

>>> myFirstObject = MyNewObjectType()
The class name uses the familiar function operator () and appears in the form of "function call. Then, the new instance is usually assigned to a variable.

Class can be very simple or complex. In the simplest case, the class is only used as a namespace ). This means that you store data in variables and group them by namespace so that they are in the same link space-the so-called relationship is identified by the standard Python period attribute.

>>> mathObj = MyData()>>> mathObj.x = 4>>> mathObj.y = 5>>> mathObj.x + mathObj.y9
The instance name mathObj associates mathObj. x with mathObj. y. This is to use the class as the namespace container. MathObj. x and mathObj. y are instance attributes, because they are not attributes of the class MyData, but unique attributes of the Instance Object (mathObj.

Ii. Method

In Python, methods are defined in class definitions, but can only be called by instances. That is to say, the final way to call a method must be as follows: (1) defining classes (and methods); (2) Creating an instance; (3) last step, use this instance to call the method.

>>> class MyDataWithMethod(object):...     def printFoo(self):...             print('You invoked printFoo()!')...
Self parameter, which exists in all method declarations. This parameter indicates the instance object itself. When you call a method using an instance, an interpreter is quietly passed to the method. Therefore, you do not need to pass self in by yourself, because it is automatically passed in. The general method requires this instance (self), but the static method or class method does not. The class method requires a class instead of an instance.

>>> myObj = MyDataWithMethod()>>> myObj.printFoo()You invoked printFoo()!
A special method _ init _ () ,__ init _ () is similar to the class constructor. After Python creates an instance, it calls the _ init _ () method during the instantiation process. When a class is instantiated, additional behaviors can be defined.

3. Create a class (class definition)

>>> class AddrBookEntry(object):...     'address book entry class'...     def __init__(self, nm, ph):...             self.name = nm...             self.phone = ph...             print('Created instance for:', self.name)...     def updatePhone(self, newph):...             self.phone = newph...             print('Updated phone# for:', self.name)...>>>
In the definition of the AddrBookEntry class, two methods are defined: __init _ () and updatePhone ().

4. Create an instance (instantiation)

>>> john = AddrBookEntry('John Doe', '408-555-1212')Created instance for: John Doe>>> jane = AddrBookEntry('Jane Doe', '650-555-1212')Created instance for: Jane Doe
If no default parameter exists, the two parameters passed to _ init _ () are required during instantiation.

V. Access instance attributes

>>> john<__main__.AddrBookEntry object at 0x01E0FB30>>>> john.name'John Doe'>>> john.phone'408-555-1212'>>> jane.name'Jane Doe'>>> jane.phone'650-555-1212'
6. method call (through an instance)

>>> john.updatePhone('415-555-1212')Updated phone# for: John Doe>>> john.phone'415-555-1212'
7. Create subclass

Subclass by inheritance is a method for creating and customizing new types. New Classes maintain all the features of existing classes without changing the definition of the original classes. The new subclass can be customized to only its specific functions. In addition to the relationship with the parent class or the base class, the Child class is no different from the common class, and the general class is also instantiated.

>>> class EmplAddrBookEntry(AddrBookEntry):...     'Employee Address Book Entry 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)...
In the above class, not only the _ init _ () and updateEmail () methods are defined, but also the updatePhone () method inherited from the AddrBookEntry.

If needed, it is better for each subclass to define its own constructor. Otherwise, the constructor of the base class will be called. However, if the subclass overrides the constructor of the base class, the constructor of the base class will not be automatically called -- in this way, the constructor of the base class must be displayed and written to be executed. Here we want to display the passing self instance object to the base class constructor, because we call the _ init _ method of the base class in a subclass instance instead of in this instance.

8. Subclass

>>> john = EmplAddrBookEntry('John Doe', '408-555-1212', 42, 'john@spam.doe')Created instance for: John Doe>>> john<__main__.EmplAddrBookEntry object at 0x01E0FC30>>>> john.name'John Doe'>>> john.phone'408-555-1212'>>> john.email'john@spam.doe'>>> john.updatePhone('415-555-1212')Updated phone# for: John Doe>>> john.phone'415-555-1212'>>> john.updateEmail('john@doe.spam')Updated e-mail address for: John Doe>>> john.email'john@doe.spam'>>>



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.