Python (3) class introduction

Source: Internet
Author: User
Tags in python

Http://docs.python.org/2/tutorial/classes.html

From the C + + point of view, all the members of Python are public, and all functions are virtual, except when declaring variables with the sign "__", which means that it is private.

1) The copy assignment of the object

Python also has a aliasing problem, aliasing is equivalent to pointing to the same object, the following code describes the difference between alias and positive copy, the general object assignment is directly with the alias to complete, except the basic type.

Shoplist = [' Apple ', ' mango ', ' carrot ', ' banana ']
mylist = shoplist # mylist is just another name pointing to the same object!
MyList = shoplist[:] # Make a copy by doing a full slice
If you want to implement true copy, refer to the code below to achieve a light copy and deep copy

>>> a = [[1], [' A '], [' a ']]
>>> import copy
>>> B = copy.deepcopy (a)
>>> b
[[1], [' A '], [' a ']]
>>> c = copy.copy (a)
>>> c
[[1], [' A '], [' a ']]
>> > a[1].append (' B ')
>>> a
[[1], [' A ', ' B '], [' a ']]]
>>> b
[[1], [' A '], [' a ']]
>>> C
[[1], [' A ', ' B '], [' a ']]


2 the definition of class

>>> class Complex:
...     def __init__ (self, Realpart, Imagpart):
...         SELF.R = Realpart
...         SELF.I = Imagpart
...
>>> x = Complex (3.0, -4.5)
>>> x.r, x.i
(3.0,-4.5)
This class also has a constructor __init__, which is called automatically when the system declares the object, such as X=complex (1,2), and we see that the function of the class has a characteristic that the method of the class must have an extra first argument (self), But when you call this method, you don't have to assign a value to this parameter, self is not a keyword in python. Self represents the address of the current object. Self can avoid global variables caused by unqualified calls.



3 Inheritance of Class

Class supports multiple inheritance

Class Derivedclassname (Base1, Base2, Base3):
    <statement-1>
    ...
    <statement-N>



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.