"0 Basics Python (second edition)" (iv)

Source: Internet
Author: User

The beginning is the advanced part.

Iv. class

1. Class

The old class was used prior to Python2.2, and the new class was used after version 2.2, but there was no problem after Python3. The following question is about the new class.

There are two ways to define a new class.

1) The definition of inheritance.

<span style= "FONT-SIZE:18PX;" >class A (object):p Assa = A () print A.__class__#<class ' __main__. A ' >print type (a) #<class ' __main__. A ' ></span>
2) Write this sentence in front of the class: __metaclass__ = = Type (means that the class defined below is a modern Class), and then define the class without having to write (object) behind the name.

<span style= "FONT-SIZE:18PX;" >__metaclass__ = Typeclass A:passa = A () print A.__class__#<class ' __main__. A ' >print type (a) #<class ' __main__. A ' ></span>
The following describes the creation of a new class. The parameters of a method in a class must include the self parameter and be the default first parameter. Def __INIT__ is called the initialization function.

<span style= "FONT-SIZE:18PX;" >__metaclass__ = Typeclass person:def __init__ (self,name): Self.name = Namedef getName (self): return Self.namedef Age ( Self,age):p rint "%s is%d years old"% (self.name,age) p = person (' why ') the print p.getname () #whyp. Age (22.5) #why is years ol D</span>

When variables in a class refer to immutable data, instance properties do not affect class properties, and class properties affect instance properties. When a variable in a class refers to a Mutable object, both the class property and the instance property can modify the object directly, thereby affecting the value of the other party.

<span style= "FONT-SIZE:18PX;" >class A (object): x = 3y = [1,2,3]a = A () a.x = 4print a.x#3print a.x#4a.y.append (4) Print a.y#[1, 2, 3, 4]print a.y#[1, 2 , 3, 4]</span>
after the class is determined or instantiated, the property can also be added and modified, by means of the operation of the class or instance's point number, i.e., Object.attribute, which can be modified and added to the property. However, if you increase the instance properties, the class properties do not change.

<span style= "FONT-SIZE:18PX;" >class A (object): x = 3y = [1,2,3]a = A () a.z = ' Why ' Print A.z#whyprint A.z#attributeerror:type object ' A ' have no attrib Ute ' Z ' a.q = 22.5print a.q#22.5print a.q#22.5</span>

namespaces because of the different objects, there are also differences, can be divided into the following types:

1) built-in namespaces (built-in namespaces): Python runs, and they exist. The namespaces for built-in functions belong to the built-in namespaces, so we can run them directly in any program, such as D (), without any action, and use them directly.

2) global namespace (Module:global namespaces): Each module creates its own global namespace, the global namespaces of different modules are independent of each other, and namespaces of the same name in different modules will not interfere with each other because of the different modules.

3) Local namespace (function&class:local namespaces): There are functions or classes in the module, and the namespace defined by each function or class is the local namespace. If the function returns a result or throws an exception, the local namespace also ends.

In addition, the problem of data rotation and scope is also discussed.

The following is a discussion of class inheritance and method rewriting, because it is similar to Java, so do not repeat.

In the old class, the multiple inheritance is based on the depth first, and in the new class is in terms of breadth first. The __mro__ property of the class can be used to obtain the class inheritance order.

<span style= "FONT-SIZE:18PX;" >class A (object):</span>
<span style= "FONT-SIZE:18PX;" >def foo (self):p rint ' foo A ' class B (object):d EF foo (self):p rint "Foo B" def bar (self):p rint "Bar B" Class C (A, b):p Asscla SS D (A, b):d EF bar (self):p rint "Bar D" class E (c,d):p assprint e.__mro__   # (<class ' __main__. E ';, <class ' __main__. C ';, <class ' __main__. D ';, <class ' __main__. A ';, <class ' __main__. B ';, <type ' object ' >) e = E () e.foo () #foo Ae.bar () #bar d</span>
In a new class, if you want to invoke the method of the parent class, you can use the Super function, especially when initializing the function. The parameters of the Super function, the first one is the class name of the current subclass, the second is self, then the dot, and the dot is followed by the method of the parent class to be called.

<span style= "FONT-SIZE:18PX;" >__metaclass__ = Typeclass person:def __init__ (self): Self.name = ' What ' Def p (self):p rint "My name is {}". Format (self.na ME) class employer (person):d EF __init__ (self): Super (Employer,self). __init__ () Self.age = 22.5def p (self):p rint "I am {} Years old ". Format (self.age) super (Employer,self). P () e = employer () E.P () # I am 22.5 years old# My name is why</span>

In Python: @staticmethod indicates that the following method is a static method, @classmethod that the following method is a class method. Static methods are still defined with DEF statements. It is important to note that the properties of instance variables, classes, and instances cannot be accessed because they do not have self in parentheses after the file name, because they all pass data with self. The parameters of the class method do not have self, but must have the CLS parameter. In a class method, you can access class properties, but you cannot access instance properties. Both methods can be called through an instance, that is, binding an instance. It can also be called through a class. See the differences between Staticmethod and Classmethod in this article on the differences between the two.

Write a document string description at the beginning of a function, class, or file, usually using a triple quotation mark. The greatest benefit of this writing is that it can be viewed with the Help () function.

<span style= "FONT-SIZE:18PX;" > "" This is Python Lesson "" "Def Start_func (ARG):" "" The "" is    a function.    "" Passclass MyClass: "" "This is    my class.    " " def my_method (Self,arg): "" "This is        my method.        " " Pass</span>

2. Polymorphism and encapsulation

The count () function is a count of the number of occurrences of an element in an object.

<span style= "FONT-SIZE:18PX;" >print "Wwhhy". Count (' W ') #2print [1,1,2,3,4].count (2) #1 </span>
the repr () function returns a string for any object that is entered. It can be used to show polymorphism.

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >def Length (x):p rint "The length of", repr (x), "is", Len (x) Length ([]) #the length of  [1, 2, 3] is  3leng Th (' why ') #the length of  "Why"  is 3length ({1: ' Why ', 2: ' ZMQ ') #the length  of {1: ' Why ', 2: ' Zmq '} is  2< /span></span>
The method of privatization in Python is also relatively straightforward, which is to double-underline the attributes (including methods, data) that are intended for privatization. You can use the property function if you want to invoke those private properties. After using @property, the method is called in the form of p.xx, as if a property is called .

<span style= "FONT-SIZE:18PX;" >__metaclass__ = Typeclass A:    def __init__ (self):        self.me = "why"        self.__name = "ZMQ"    @property    def name (self):        return Self.__nameif __name__ = = "__main__":    p = A ()    print P.name#zmq</span >

3. Special Methods

Here are a few special methods:

1) __dict__: The properties of the object are saved. The following is a comprehensive example, where the properties and methods are similar.

<span style= "FONT-SIZE:18PX;" >class A (object): Name = ' Why ' Print a.__dict__#{' __dict__ ': <attribute ' __dict__ ' of ' A ' objects>, ' __module__ ': ' __main__ ', ' __weakref__ ': <attribute ' __weakref__ ' of ' A ' objects>, ' name ': ' Why ', ' __doc__ ': None}print a.__dict_ _[' name '] #whyprint A.name#whya = A () print a.__dict__#{}print a.name#whya.name = ' zmq ' Print a.__dict__#{' name ': ' ZMQ '} Print a.__dict__[' name '] #zmqprint a.name#zmqprint a.__dict__#{' __dict__ ': <attribute ' __dict__ ' of ' a ' objects> ' __module__ ': ' __main__ ', ' __weakref__ ': <attribute ' __weakref__ ' of ' A ' objects>, ' name ': ' Why ', ' __doc__ ': none}p Rint a.__dict__[' name '] #whyprint a.name#whydel a.nameprint a.__dict__#{}print a.name#whya.age = 22.5print a.__dict__#{ ' Age ': 22.5}print a.age#22.5print a.__dict__["age" #KeyError: ' Age ' print A.age#attributeerror:type object ' A ' have no att Ribute ' age ' a.major = ' computer ' Print a.__dict__#{' age ': 22.5}print a.major#computer</span>
2) _slots__: The ability to restrict the definition of attributes, the most important aspect of programming is to optimize memory usage. _slots__ has managed to keep the instance properties tightly controlled, but more fundamentally, the memory is optimized. This optimization results in a large number of instances.

<span style= "FONT-SIZE:18PX;" >class A (object): __slots__ = (' name ', ' age ') print a.__slots__# (' name ', ' age ') A = A () print a.__slots__# (' name ', ' age ') A.name = ' Why ' print a.name#why# a.name = ' zmq ' #AttributeError: ' A ' object attribute ' name ' is Read-onlya.age = 22.5print A . Age#22.5print A.age#<member ' age ' of ' a ' objects>a.age = 23print a.age#23a.major = ' computer ' #AttributeError: ' A ' O Bject has no attribute ' major ' </span>
3) __setattr__ (Self,name,value): This method is called if you want to assign a value to name.

4) __getattr__ (Self,name): This method is called when name is accessed and it does not exist.

<span style= "FONT-SIZE:18PX;" >class A (object):d EF __getattr__ (self, name):p rint ' You use GetAttr ' Def __setattr__ (self, name, value):p rint "Your use s Etattr "self.__dict__[name] = Valuea = A () a.x#you Use getattra.x = 3#you use Setattrprint a.x#3</span>

5) __getattribute__ (self,name): called automatically when name is accessed (note: This can only be used for modern classes), regardless of whether the name exists or not.

6) __delattr__ (self,name): If you want to delete name, this method is called.

<span style= "FONT-SIZE:18PX;" >class B (object):d EF __getattribute__ (self, name):p rint "You are useing getattribute" return object.__getattribute__ (self, name) B = B () b.y#you is useing getattribute     attributeerror: ' B ' object has no attribute ' y ' b.y = 4print b.y#4&l T;/span>
Its properties are obtained through an instance, and if there is a corresponding property in __dict__, the result is returned directly, and if not, it is found in the class attribute. If the __getattr__ () method is not defined, the Attributeerror is raised.
<span style= "FONT-SIZE:18PX;" >__metaclass = Typeclass a:name = ' why ' def __getattr__ (self,key): if key! = ' name ': return "Check Again" a = A () print a.na Me#whyprint A.major#check again</span>
4. Iterators
__iter__ is a special method of an object, which is the basis of an iterative rule. If the object does not have it, it cannot return to the iterator, and without the next () method, it cannot iterate. Allows you to iterate over objects that you write.
<span style= "FONT-SIZE:18PX;" >__metaclass__ = Typeclass a:def __init__ (self,n): self.i = 0SELF.N = Ndef __iter__ (self): return to Selfdef next (self): if s elf.i < SELF.N:I = self.iself.i + 1return ielse:raise stopiteration () if __name__ = = "__main__": A = A (7) print a.next () p Rint A.next () print "------------" for I in A:print i# 0# #------------# * 3# 4# AA 6</span>

There are also two very typical built-in functions for the differences between lists and iterators: Range () and xrange (). Range () returns a list, xrange () returns an object that is slightly faster at the time of the loop and has a higher memory efficiency. That is, the list obtained through range () is read into memory one time, and the object returned by Xrange () requires a numeric value to return a numeric value. The following example will demonstrate the advantages of the xrange () function.

<span style= "FONT-SIZE:18PX;" >__metaclass__ = TypeA = Range (4) b = xrange (10000) print zip (A, b) 3[(0, 0), (1, 1), (2, 2), (3, 3)]</span>
5. Generator
The generator must be iterative and has better execution efficiency than the list. The representation is the {} that resolves the list to ().

<span style= "FONT-SIZE:18PX;" ><span style= "FONT-SIZE:18PX;" >a = (i**2 for I in range (4)) for I in A:print I, #0 1 4 9print "" For I in A:print i,#</span></span>
yeild keyword is the identity of the generator. The function return value is an object of a generator type, which is an iterator. We call a function that contains a yield statement as a generator. A builder is an iterator that is defined with normal function syntax.

<span style= "FONT-SIZE:18PX;" >def A (): yield 0yield 1yield 2a = a () print a.next () #0print a.next () #1print a.next () #2print a.next () #StopIteration < /SPAN>
discover yield Besides being the generator's flag, there is also a function that returns a value. Return ends execution of the function body, and yeild suspends temporarily until the next call to the next method.

<span style= "FONT-SIZE:18PX;" >def A ():p rint "before" for I in Range (4): Return iprint "after" AA = A () #beforeprint aa#0print aa#0def B ():p rint "before" For I in range (4): Yield iprint "after" BB = B () #beforeprint bb.next () #0print bb.next () #after 1</span>


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"0 Basics Python (second edition)" (iv)

Related Article

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.