I java,net get started, of course Python also want to learn well, these days to introduce the Python object-oriented
Object-oriented programming requires the use of classes, classes and instances, and with classes we have to create an instance to invoke the method of the class. First look at the structure pattern of the class
Property: A method is disguised as a property that does not have an intrinsic elevation at the level of the code, but makes it look reasonableMasquerading as a propertyClass Person:def _ _init_ _ (Self,name, weight,hight):Self.name=nameSelf.weight=weightSelf.hight=hightdef BIM (self):The BMI for return%s is%s% (Self.name, (Self.wejght/(self.hight**2)))P1=person ("haha", 50,1.63) # instantiates an objectP1.b
__getattr__Called when a class attribute is not foundClass Beimenchuixue: def __init__ (self, name): self.name = name def __getattr__ (self, item): print ("% s not find ", item) Raise Exception (" instance method not found ") if __name__ = = ' __main__ ': Bei_men_chui_xue = Beimenchuixue (" North Gate blowing Snow ") print (bei_men_chui_xue.name) # without this property
In general, in Python, the access rules for class instance properties are fairly straightforward.
However, there are still some areas that are not very intuitive, especially for C + + and Java programmers.
Here, we need to understand the following areas:
1.Python is a dynamic language, and any entity can dynamically add or remove attributes.2. A
Python version: 3.5.2If we had a student class and defined a score attribute in it, but the score attribute would be revealed, there was no way to check the parameters, resulting in the result being arbitrarily changed:stu = Student()stu.score = 9999This is obviously illogical, in order to limit the scope of the score, you can set the score by a Set_score () method, and get the score by a Get_score () metho
and after executionReturn "Return wrapper@ Makebold@ MakeitalicDef say ():Return "hello"Print say ()# Output: # EquivalentDef say ():Return "hello"Say = makebold (makeitalic (say ))Print say ()# Output: Built-in decorator
There are three built-in decorators: staticmethod, classmethod, and property. They are used to convert the instance methods defined in the class
The Magic method for Python class property access:1. __getattr__ (self, name)-Defines the behavior when a user attempts to acquire a nonexistent property2. __getattribute__ (self, name)-Defines the behavior when the properties of the class are accessedNote: When __getattr__ and __getattribute__ are overridden at the sa
In general, the access rules for class instance properties are more intuitive in python.
However, there are still some areas that are not intuitive, especially for C + + and Java programmers.
Here, we need to understand the following areas:
1.Python is a dynamic language in which any entity can dynamically add or remove attributes.2. A
#!/usr/bin/env python#-*-coding:utf-8-*-#====> __setattr__ overriding a magic method called when setting class object property values __getattr__ (self,name) Get class properties # __getattribute__ (Self,name) is called before the property is obtained, __getattr__ is calle
"double underline" for the special method in Python, such as __init__ () represents the constructor of the class.classB:def __init__(self): self.__private=0 Self._private=1def __private_method(self):Pass defPublic_method (self):PassSelf .__private_method() b=B ()#print (b.__private) #双下划线, no access to dataPrint(b._private)#single underline, you can access theIt is also important to note that private attributes cannot be accessed, such asclassB:de
Python are not the same as those in Java and C ++, functions in Python can be passed to another function as parameters like common variables. For example:
def foo(): print("foo")def bar(func): func()bar(foo)
Officially return to our topic. The decorator is essentially a Python function or
decorator.
Timeout detection logic: Start a new sub-thread to execute the specified method. The main thread waits for the running result of the sub-thread. If the sub-thread has not completed execution within the specified time, it is deemed as timeout, throw a timeout exception and kill the sub-thread. Otherwise, the return value of the method executed by the sub-thread is returned.
In the implementation process, it is found that there is no way to
Python deep learning decorator and python deep learning and Decoration
Decorator is an advanced Python syntax. The decorator Can process a function, method, or class. In
#Leave me alone#After the function runsYes, that's it, it's so simple. @decorator is an abbreviation for the following form:
Another_stand_alone_function = My_shiny_new_decorator (another_stand_alone_function)The adorner described here is a Python variant of the adorner design pattern. There are some classic design patterns in Python that make it easier to devel
://www.lai18.com//date 2015-06-21import timedef foo(): start = time.clock() print 'in foo()' end = time.clock() print 'used:', end - start foo()
Very good, functionality looks impeccable. But B suddenly didn't want to look at this function at the moment. He became more interested in another function named foo2.
What should we do? If you copy the newly added code to foo2, this makes a big mistake ~ Isn't copying anything the most annoying! What if B continues to read other functions
set of functions and called.
Higher order function : one function accepts another function as a variable. function is variable
all objects in Python (objects, and then the problem with object programming). When a function is defined, the function is the first class object/class object. The so-called first class
An adorner (decorator) is an advanced Python syntax. Adorners can be used to process a function, method, or class. In Python, we have several methods for working with functions and classes, such as in Python closures, where we see the function object as the result of a funct
parameters and has returned values. The task of perfecting it is handed over to you :)
2. Additional Python support
2.1. Syntactic sugar
The above Code seems to be no longer streamlined, and Python provides a syntax sugar to reduce the input of characters.
Copy codeThe Code is as follows:Import timeDef timeit (func ):Def wrapper ():Start = time. clock ()Func ()End = time. clock ()Print 'used: ', end-startR
ArticleDirectory
1. Origin
2. Make the code more elegant.
3. Make the code more elegant.
4. Add Parameters
5. Decorated functions with return values
6. apply multiple decorators
7. Flexible Use
To understand Python's decorator, you must first know that the function is also an object in Python, so you can
Copy a function to a variable
Use a function as a parameter
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.