Python: Class, pythonclass

Source: Internet
Author: User

Python: Class, pythonclass

Like JavaScript, Python is a process-oriented language, an object-oriented language, and a dynamic language. In most object-oriented languages, Class is essential. Object-oriented has three main features: encapsulation, inheritance, and polymorphism. What is the Class in Python?

  • 1. Class composition
  • 2. Class getter and setter
  • 3. Class inheritance
  • 4. Operator Rewriting
  • 5. Simulate private attributes
  • 6. static method
1. Class composition

Let's look at an example:

Class Person (object): id = ''name ='' age = 3 # equivalent to <init> in Java, that is, the constructor def _ init _ (self, id, name, age): print ("init a Person instance") self. id = id self. name = name self. age = age def show (this): print (this) # print (this. toString () # def toString (self): # return "id :{}, name :{}, age :{}". format (self. id, self. name, self. age) # equivalent to toString def _ str _ (self): # return self. toString () return "id :{}, name :{}, age :{}". format (self. id, self. name, self. age) # equivalent to the finalize method in Java. When a del instance is called, def _ del _ (self): print ("finally a Person instance") self. id = None self. name = None self. age = None self = None

 


The following describes the classes in Python by comparing Java:

1) in Class, including attributes and methods, they are all public. In Python Class, there are no modifiers such as private and protected.

2) _ init _ is a constructor. When the constructor is called, _ init _ is automatically called __. It is equivalent to <init> in Java. When creating a Python object, you do not need to use new like Java.

3) _ del _ Is A destructor. When del instance is used, _ del _ is automatically called __. It is equivalent to finalize in Java.

4) to obtain the string representation of an object, _ str _ is called __. It is equivalent to the toString in Java.

5) The first parameter of the class method is self, which is equivalent to this in Java. In fact, the first parameter of the instance method in Java is this, but it is hidden. If you understand the JVM runtime, or have used bytecode tools such as javassist or asm, yes. In the above example, when p1.show () is run, it can be understood as executing Person. show (p1 ). It doesn't mean that you must write it as self. You can also write this or any other form that satisfies the variable name. However, we usually agree that writing is commonly known as self, keeping the encoding style uniform and facilitating others to understand the code.

6) _ init __,__ del __,__ str _ is not required.

7) All attributes must have initial values.

 

2. Class getter and setter

Java and JavaScript ES6 support setter and getter. Python is also supported.

Class Person (object): id = ''name ='' age = 3 # equivalent to <init> in Java, that is, the constructor def _ init _ (self, id, name, age): print ("init a Person instance") self. id = id self. name = name self. age = age def show (this): print (this) # print (this. toString () # def toString (self): # return "id :{}, name :{}, age :{}". format (self. id, self. name, self. age) # equivalent to toString def _ str _ (self): # return self. toString () return "id :{}, name :{}, age :{}". format (self. id, self. name, self. age) # equivalent to the finalize method in Java. When a del instance is called, def _ del _ (self): print ("finally a Person instance") self. id = None self. name = None self. age = None self = None def _ get _ (self, name): print ("invoke in _ get _") print (self. _ dict _) return 1111 def _ getattr _ (self, name): print ("invoke in _ getattr __") return 1111 def _ getattribute _ (self, name): print ("invoke in _ getattribute _") print (object. _ getattribute _ (self, name) print ("after invoke in _ getattribute _") return object. _ getattribute _ (self, name)

For legacy classes, the order of access properties is:

1) direct access to properties

2) Access _ getattr __

For new classes, the order of access attributes is:

1) _ getattribute

2) direct access to properties

3) _ getattr __

Remember, if _ getattribute __is written, the last sentence must be object. _ getattribute (self, name); otherwise, 'xxxtype' object is not callable. It exists, more like being used as an interceptor.

3. Class inheritance

C ++ is multi-inheritance, and Java is single-inheritance. Python draws on the Multi-inheritance mode of C ++.

In the inheritance structure, when accessing attributes and methods, they are the same as those in Java. They are first searched for from the parent class.

Because multi-inheritance is supported, which one will be accessed when one attribute or method exists in multiple parent classes?

To answer this question, you must first know the order of search attributes and methods. The depth-first search algorithm is used.

That is, A class A (S1, S2, S3): pass; when you want to call an attribute, it will first be found from A, and then from S1, if not, start from S2, and so on.

 

In the case of multiple inheritance, what is the difference if the _ getattr _ method is overwritten by A, S1, S2, and S3? The query order remains unchanged:

1) The direct attribute of A cannot be found, and then A. _ getattr __

2) The direct attribute of S1 cannot be found, and then S1. _ getattr __

3) The direct property of S2 cannot be found, and then it is S2. _ getattr __

4) S3's direct attribute, which cannot be found and then S3. _ getattr __

 

For constructor _ init __, when constructing an instance, the _ init _ of the parent class will not be called first like Java __.

class Student(Person):    def __init__(self, id, name, age,email):        print("invoke in Student __init__")        super(Student, self).__init__(id, name, age)        self.email = email

 

Are there super () in Java and Python? Can we use super? If the constructor of the parent class cannot be automatically called, the _ init _ should be overwritten and all attributes should be allocated. What should we do? It can only be called programmatically.

Super (class, instance), the function is used to findNext parent class of the specified classTo call the method on the specified instance.

For example, in the above example, the inheritance relationship is as follows: Student> Person> object. Self is a Student object, super (Student, self ). _ init _ (id, name, age): Find the _ init _ method of the next parent class (I .e. Person) of Student, then the _ init _ method is called on self.

 

Note that:

1)SuperThe two parameters of the function cannot be incorrect. Two conditions must be met, and the secondInstanceIt should be the instance of the class represented by the first parameter (or the instance of its subclass ).

2) Super can only be used in new classes.

 

 

4. Operator Rewriting

Both. Net and Scala programming languages Support operator rewriting. It may be hard to understand if you have never touched these things. In fact, you only need to look at the operator as a method. From this perspective, Java also supports operator rewriting, but this feature is not exposed to users. For example, String concatenation +, which is actually the StringBuilder. append method called to traverse the foreach of the set. It actually calls iterator. Since the operator rewriting is mentioned, it must also be supported in Python, And it exposes this feature.

 

Python String overrides several operators:

+ String concatenation * copy multiple equal to = compare string content> string comparison <string comparison

So how can we rewrite operators?

As mentioned above, operators are considered as a method. The rewrite operator is the rewrite method.

Common Operator Overloading is listed below:

Overload Method

Description

Call

_ Init __

Constructor

Object creation, X = Class ()

_ Del __

Analysis Method

Object recycling, or del X

_ Add __

Operator +

X + Y, X + = Y

_ Iadd __

Enhanced +

X + Y, X + = Y

_ Radd __

Left +

Noninstance + Y

_ Or __

Operator | (bit OR)

X | Y, X | = Y

_ Repr __,__ str __

Print, convert

Print (X), repr (X), str (X)

_ Getattr __

Point Operator

Get attributes

_ Setattr __

Value assignment operator

Set attributes

_ Call __

Function call

Y ()

_ Len __

Length

Len (X)

_ Cmp __,

_ Lt __,

_ Eq __

Comparison

X <Y

X = Y

_ Getitem __

Index Operators

X [name]

_ Setitem __

Index Assignment

X [Y] = Z

_ Iter __

Iteration

Loop, iteration, etc.

 

Use _ getitem _ to enable the object to be accessed by indexing?

The test is as follows:

 

class Student(Person):    def __init__(self, id, name, age,email):        print("invoke in Student __init__")        super(Student, self).__init__(id, name, age)        self.email = email    def __getitem__(self, name):        return self.__dict__[name] + "_suffix"

Run the test:

  

import modelStudent = model.Students = Student('0001', 'fjn', 20, 'fs1194361820@163.com')s.show()print(s["email"])

The result is: fs1194361820@163.com _ suffix

 

5. Simulate private attributes

Through the above study, we learned that Python's attributes and methods are all public, which is the same as JavaScript. After writing Java for a long time, how can I waste the benefits of private attributes. So how can we simulate a private one?

There are two ways to simulate, both of which are similar to the concept in JavaScript.

Method 1: when an object is used, attributes are directly added.

Method 2: Use the object's _ dict __

 

6. Static Method

In java, the instance method and class method are differentiated. The specific method is to add a static modifier to the class method. There is no static in python, so how to implement the static method.

As mentioned above, when declaring an instance method, the first parameter is self. In python, the essence of an instance method is to call a class method.

p1=Person(‘a’,’b’,23)Person.show(p1)

 

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.