Python Learning Notes-object-oriented basics

Source: Internet
Author: User

1. Classes and instances

Definition of Class 1.1

Class is defined using the Class keyword followed by the name (usually beginning with a capital), followed by the class (object) name inherited by the class and not inheriting the object class.

When instantiated is the class name + (), parameters need to be passed in parameters.

Class Student (object):    Pass
bart = Student()

The properties of the class are defined in the _init_ method (equivalent to the constructor method of Java), the first parameter of the method is always self, and the corresponding parameter must be passed in when instantiating (except for self)

Class Student (object):    def __init__ (self, Name, score):        self.name = name        Self.score = Score
bart = Student(‘Bart Simpson‘, 59)

1.2 Parameters of the method

The first parameter of a class method must be self and not be passed in. The rest of the arguments are the same as normal functions, and you can use default parameters, variable parameters, and keyword parameters.

1.3 About instance variables

Because Python is a dynamic language that allows new variables to be added to an instance, the number and names of two instance variables for a class are not necessarily the same.

1>>> Bart = Student ('Bart Simpson', 59)2>>> Lisa = Student ('Lisa Simpson', 87)3>>> Bart.age = 84>>>Bart.age586>>>Lisa.age7 Traceback (most recent):8File"<stdin>", Line 1,inch<module>9Attributeerror:'Student'object has no attribute' Age'

2. Access Restrictions

In Python, the variable name of an instance, if __(双底杠) it begins, becomes a private variable (private) that can only be accessed internally and cannot be accessed externally. External to get or change the value of the variable can be obtained through the Set,get method, a parameter check is also required inside the set method. In addition, the double-bottom bar at the end of the double-ended variable is a special variable, the name of the variable should not be named in this way.

1 class Student (object): 2 3     def __init__ (self, Name, score): 4         Self. __name = name5self         .  __score = Score

3. Inheritance and polymorphism

Python's inheritance is similar to polymorphism and Java, following the "open and Close principle": opening to the extension, enclosing the modification. However, Python supports multiple inheritance, and if the parent class has the same method, the call will be searched from left to right, and the remainder will be followed specifically.

4. Get Object Information

4.1 type function: Type (object), which returns the types

4.2 isinstance Function: Isinstance (instance, class name), returns a Boolean value

4.3 dir function: Dir (object), returns a string containing the properties of all methods of the object list

4.4 __xxx__ 's properties and methods are used in Python for special purposes, such as the __len__ method, which is equivalent to the following two usages: (a person thinks that one is a function, one is a class method)

1 >>> len ('abc')2 33'ABC  '. __len__ ()4 3

4.5 getattr() , setattr() andhasattr()函数:可以直接操作一个对象的状态。如下所示:

1>>> hasattr (obj,'x')#Do you have attribute ' x '? 2 True3>>>obj.x495>>> hasattr (obj,'y')#Do you have attribute ' y '? 6 False7>>> setattr (obj,'y', 19)#set a property ' Y '8>>> hasattr (obj,'y')#Do you have attribute ' y '? 9 TrueTen>>> getattr (obj,'y')#Get property ' Y ' One19 A>>> OBJ.Y#Get property ' Y ' -19

You can pass in a default parameter and, if the property does not exist, return the defaults:

1 ' Z ' # gets the property ' Z ', if it does not exist, returns the default value 404 2 404

Python Learning Notes-object-oriented basics

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.