Python-6 Object-Oriented programming

Source: Internet
Author: User

1-Classes and instances

classStudent (object):def __init__(self, Name, score):#The first argument of the _init__ method is always self, which represents the created instance itselfSelf.name =name Self.score=scoredefPrint_score (self):Print('nams:%s, score:%s'%(Self.name,self.score))defGet_grade (self):if(Self.score >=90):            return 'A'        elif(Self.score >= 60):            return 'B'        Else:            return 'C'#calledStu = Student ('Qinzhongbao', 79) Stu.print_score ()Print(Stu.get_grade ())

2-Access Restrictions
The variable name of the example becomes a private variable (private) if it starts with __, only the inside can access

classPerson (object):def __init__(self, Name, score): Self.__name=name self.__score=scoredefPrint_score (self):Print('name:%s,score:%s'% (self.__name, self.__score))    defget_name (self):returnSelf.__name Person= Person ('Fengyong', 88) person.__name='NewName' #Modifying ValuesPrint(person.__name)#NewNamePrint(Person.get_name ())#Fengyong modified value does not take effect

3-Inheritance and polymorphism

classAnimal (object):#Inherit Object    defRun (self):Print('Animal is running')        classDog (Animal):#Inherit Animal    defRun (self):Print('Dog is running')        classCat (Animal):defRun (self):Print('Cat is running')        defRun (animail): Animail.run () Animal=Animal () run (Animal) run (Dog ()) Run (Cat ( ))#for dynamic languages such as Python, it is not necessarily necessary to pass in the animal type. #we just need to make sure that the incoming object has a run () method.

4-Get object information

4.1 Using the type () function

Type (123)#<class ' int ' >Type'Str')#<class ' str ' >Type (123) ==type (456)#TrueType'ABC') ==str#TrueType'ABC') ==type (123)#FalseImportTypesdeffn ():Passtype (FN)==types. Functiontype#TrueType (ABS) ==types. Builtinfunctiontype#TrueTypeLambdaX:X) ==types. Lambdatype#TrueType ((x forXinchRange (ten)) ==types. Generatortype#TrueDir (Types)#to view types common constants

4.2 Isinstance Use

# with Isinstance, type () is inconvenient for class inheritance # If the inheritance relationship is: Object, Animal, Dog, Husky  and # true # judgment is a type of isinstance (b'a'#True

4.3 dir using

# If you want to get all the properties and methods of an object, you can use the Dir () function, which returns a listdir ('ABC') containing the string

4.4 Len (obj)

We write our own class, if we want to use Len (MYOBJ), we write a __len__ () method

4.5 getattr (), SetAttr () and hasattr ()

It is not enough to simply list properties and methods, with GetAttr (), SetAttr (), and hasattr (), we can manipulate the state of an object directly:

classMyObject (object):def __init__(self): self.x= 9defPower (self):returnself.x *Self.xobj=MyObject () hasattr (obj,'x')#Do you have attribute ' x '? TrueSetAttr (obj,'y', 19)#set a property ' Y 'GetAttr (obj,'y')#gets the property ' y ' if this property does not exist to report an exceptionGetAttr (obj,'Z', 404)#gets the property ' Z ', if not present, returns the default value of 404,
Instance properties and Class properties
 class   Student (object): Name  = " fengyong        #    Stu  = Student () stu.name  #  fengyong  stu.name =  " new Name   " stu.name  #  new Name  del  (stu.name) #   Delete bound properties  stu.name #  

As can be seen from the above example, when writing a program, do not use the same name for instance properties and class properties, because instance properties of the same name will mask the class properties, but when you delete the instance properties, and then use the same name, access to the class property

Python-6 Object-Oriented programming

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.