Python Objects and classes

Source: Internet
Author: User

All data in Python is in the form of an object, and the object is an instance of the class.

Defining classes (Class)

Use class to define a class.

For example, define a cat class, as follows:

class Cat ():
def __init__ (self): self.name = name

Create an instance of the two cat class Cat1,cat2, as follows:

CAT1 == Cat (' Momo ')

The __init__ in the class is an initialization function that executes when the instance is created. Its first argument must be self.

Inherited

A class can inherit another class, and the inherited class can be called the ' parent class ' or ' base class '. New classes that use inheritance automatically get all the methods in the old class without having to make any replication. In the new class, you can define a new method or modify the inherited method, overwriting the original method.

In Python, all classes inherit the object class.

The following is an example of a simple class inheritance.

class Cat (): def __init__ (self):     = Name
Def play ():
Print ("I like Play")
class Bosscat (Cat): def play (ball):
Print ("I like play%s",%ball)

Bosscat's Play method covers the Cat class's play method, so the two classes ' respective objects perform a different performance when performing play.

Using the Super method

The __init__ () method in the subclass (if defined) overrides __init__ () in the parent class. If the __init__ () method of the subclass inherits the arguments of the parent class's __init__ () method, you can use the Super method, as follows:

class Person ():     def __init__ (self,name):         = name        class  Emailperson (person):    def__init__( Self,name,email):        super (). __init__ (name)         = Email

Access and settings for properties

All of the features in Python are public, and if you want to implement some private properties in your class, you can:

1 getter method and setter method

Like what:

>>>classPerson (object):def __init__(self,name,age): Self.name=name Self.age= Agedefget_name (self):returnSelf.namedefSet_name (self,name): Self.name=name>>> perter= Person ('Peter', 28)>>>Perter.name'Peter'>>> Perter.name ='Perter'>>>Perter.name'Perter'>>>

2 use @property to get Properties, @xxx. Setter to set property values.

Like what:

classStudent (object): @propertydefBirth (self):returnSelf._birth @birth. SetterdefBirth (self, value): Self._birth=value @propertydefAge (self):return2014-Self._birth>>> S1 =Student ()>>> S1.birth = 1989>>>S1.birth1989>>>S1.age25>>> S1.birth = 1990>>>S1.birth1990>>>S1.age24>>> S1.age = 26Traceback (most recent): File"<pyshell#15>", Line 1,inch<module>S1.age= 26Attributeerror:can'T set attribute

3 Use ' __ ' to define internal private/hidden properties.

As follows: Direct access to the properties defined by __ will be an error.

>>>classPerson (object):def __init__(self,input_name,age): Self.__name=input_name self.__age=Age @propertydefname (self):returnSelf.__name@name. Setterdefname (self,input_name): Self.__name=Input_name>>> Peter = Person ('Peter', 29)>>>Peter.name'Peter'>>> Peter.__nameTraceback (most recent): File"<pyshell#24>", Line 1,inch<module>Peter.__nameAttributeerror:' Person'object has no attribute'__name'

Instance method/class method/static method

instance method (instance): The method that takes self as the first argument. When the method is called, Python passes the object that invokes the method as the self parameter.

Class method: A method that uses the @classmethod adornment. Note that the first parameter of a class method is the class itself CLS.

>>>classTeamA (): Num=0def __init__(self): Teama.num+ = 1@classmethoddefcounter (CLS):Print("instance number is:%s"%cls.num)>>> a1=TeamA ()>>>Teama.counter () instance number is: 1>>> A2 =TeamA ()>>>Teama.counter () instance number is: 2>>>

static method: Modified with @staticmethod.

Python Objects and classes

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.