程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Is the attribute in C the same as the decorator in python/typescript

編輯:Python

Preface

Recently, I have succeeded in 「 Front end leader 」 Into the C# The pit of ( Actually, the front-end leader started from cocos turn unity The game developed )

One day ,「 Front end leader 」 After seeing this code, I asked a question :[ This is a decorator ]?

[HttpGet]
public Response Get() {
return ...
}

My first reaction was not , This thing is C# It's called in Chinese “ characteristic ”( English name Attribute, Hereinafter collectively referred to as features ), stay Java Middle call annotation , Although the writing and Python/TypeScript It's about the same , But the implementation method should be different in the impression .

But what we study in science and engineering is to be rigorous , You can't just rely on experience and feeling , So , I checked the information , I read the recommendation of Yangxu 《C# in nutshell》 This book , It not only confirms the answer to this question , Also on the Attribute With more information .

About AOP

“ characteristic ”、 Decorator , In fact, they are all decorator patterns in design patterns , It's also AOP thought .

AOP yes Aspect Oriented Programming, That is, face-to-face programming .

AOP Break the system down into different concerns , Or it's called a section (Aspect), It's a kind of At run time , Dynamically cuts code into the specified method of the class 、 Programming ideas at specified locations

For example, there is now a website , There are shopping 、 social contact 、 Games and other functions are open to all users , It is now necessary to restrict the use of several of these functions only by senior members , We can add... To each module if Judge , But it's too intrusive , And will cause a lot of duplicate code ; Switch to AOP The way is to use decorators , Just add restrictions where senior members are needed ~

Specific differences

Let's first look at the differences in grammar

Python The decorator

First look at it. Python Decorator in , stay Python The middle function is a first-class citizen , Decorator is also a function , Another function is embedded inside

def outer(func):
def inner():
# ... Some codes
result = func()
return result
return inner

When you use it

@outer
def test():
print('test')

Usage grammar and Java The same as the notes , With @ start

Actually, this is a grammar sugar , The actual effect is equivalent to

outer(test)

take test Function is passed to decorator as an argument , The execution sequence of this code is as follows :

  • def outer(func): Decorator definition
  • @outer: Decorator grammar sugar , Direct execution outer function , take test Function passed in as argument
  • outer: Execute decorator syntax rules , take test Replace function with inner function
  • inner: perform inner function code
  • test: according to inner This line of code in :result = func(), perform test function code
  • return

stay Python In this dynamic language , Implementing decorator patterns is really easier than static languages , The decorated content is passed into the decorator as a parameter , Decorators can directly access the decorated content for some processing .

C# Of “ characteristic ”

C# in ,“ characteristic ” Is a class , Inherited from Attribute class , Then you can include any attribute fields you want

use AttributeUsage Characteristics of modified , You can specify which code elements this feature can decorate

[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
public class DemoAttribute : Attribute {
public DemoAttribute(string param1) {
this.param1 = param1;
} public string param1 { get; set; }
}

Parameters in construction method , Is the parameter passed in when using the feature , Such as this :

[DemoAttribute("class")]
public class DemoClass {
[Demo("method")]
public void Method1() {
}
}

PS: You can omit the following when using the feature "Attribute", therefore DemoAttribute and Demo It's the same thing

This will not produce any effect after writing

Because the characteristic is only a simple decoration

When the code is running ,C# The compiler instantiates DemoAttribute This class , And then instantiate DemoClass This class , And in DemoAttribute You can't get the decorated content inside .

In order to make the decoration effective , You need to use reflection in combination ~

Reflection means that a program can access 、 The ability to detect and modify its own state or behavior .

Through the following code, you can get the decoration in DemoClass Characteristics of

var info = typeof(DemoClass);
var attributes = info.GetCustomAttributes(true);

The decorated method can be obtained through the following code , And decoration parameters

foreach (var methodInfo in typeof(DemoClass).GetMethods()) {
var attribute = (DemoAttribute) Attribute.GetCustomAttribute(methodInfo, typeof(DemoAttribute));
if (attribute != null)
Console.WriteLine(" Method {0} Be decorated , Decoration parameters {1}", methodInfo.Name, attribute.param1);
}

After getting this information , Some more processing is done through other functions provided by reflection , That's what we call AOP

Summary

therefore ,C# Characteristics and Python/TypeScript Decorator in , Although the writing and usage are different , But all the same , The goals to be achieved are indeed similar .

But it is not rigorous to say the same thing , So it should be the same thing , But they are all implemented in their own languages AOP The way .

Reference material

  • C# Of Attribute and Typescript Comparison of ornaments of :https://blog.csdn.net/weixin_43263355/article/details/110137016
  • C# How to realize the similar Python Decorator in :https://www.zhihu.com/question/36211661
  • AOP Section oriented programming :https://bbs.huaweicloud.com/blogs/289045

C# Medium Attribute And Python/TypeScript Is the decorator in the same thing

  1. guxh Of python Note 3 : Decorator

    1, Function scope This situation can be carried out smoothly : total = 0 def run(): print(total) This kind of situation can report a mistake : total = 0 def run(): print(total) tot ...

  2. python Function and method decorators

    I used to use python Write a simple Fibonacci sequence of recursive implementation ( as follows ), It's found to be very slow . def fib_direct(n): assert n > 0, 'invalid n' if n < 3 ...

  3. Python Learning notes 012—— Decorator

    1 Decorator 1.1 Decorator definition How to dynamically add functions during code running , be called “ Decorator ”(Decorator). 1.2 Decorator classification Decorator : Function decorator , Class decorator , Function decorator , Class decorator Decorator : Function decoration function ...

  4. python Design patterns of the built-in decorator use ( Four )

    Preface python There are a lot of built-in decorations inside , They all have special functions , Let's summarize it . Series articles python The singleton pattern of design pattern ( One ) python Summary of common creation patterns of design patterns ( Two ) python Decoration of design patterns ...

  5. python 3.x Decorator notes for

    Today I learned python The decorator , I feel this thing is a little complicated , So write it down , Convenient for future search . Although the title is python 3.x The decorator , But I haven't used it much python 2.x, I think it should be with python ...

  6. Python Functional programming —— Closures and decorators

    Python Functional programming -- Closures and decorators One . Closure About closure , That is, the function definition and function expression are in the function body of another function ( Nested function ). and , These inner functions have access to all the local variables declared in the outer function they are in . Parameters . When one of them ...

  7. python Basics - Built in decorator classmethod and staticmethod

    Object oriented programming classmethod and staticmethod classmethod and staticmethod All are python Built-in decorator classmethod The role of : Load the methods defined inside the class ...

  8. python Closure of 、 Decorator

    One . Study Python Found the function inside , You can also write functions , And it can return the function . I think it's quite novel , Mainly in the exploration of decorators ( It's kind of like Java Annotations ) When , This understanding is still very important , So here's a record of . Two . Closure 1) First ...

  9. Python Introduction Python Three major instruments And Decorator

    Python Introduction Python Three major instruments And Decorator 1. Open and closed principle : (1) Code extension is open ​ Any program , It's impossible to have all the functions in mind at the beginning of the design without any update or modification in the future . So we have to allow generation ...

  10. Python Modular programming and decorator

    Python Modular programming for Let's first introduce the application scenario of modular programming with an example , There's one called requirements.py Of python3 file , Two of them are used to print a string in different order : # r ...

Random recommendation

  1. The Engine Document of JustWeEngine

    JustWeEngine - Android FrameWork An easy open source Android Native Game FrameWork. Github Game core ...

  2. python Use of reflection

    Reflection is a feature found in many programming languages , stay Python Of course, there is no exception . In fact, many functions in the programming language can be verified with simple code . stay code Before code , First, let's briefly understand several properties of lower reflection . hasattr(obj,name_ ...

  3. Alibaba open source technology WebX

    0. WebX The project is now open source , Project open source address :https://github.com/webx/citrus-sample.git Project reference documents :http://www.openwebx.org/docs ...

  4. SharePoint be based on windows How to verify through group policy IE Automatically log in with the current domain account SP Site

    Through group policy IE Automatically log in with the current domain account SP Site 1. Running in operation MMC, start-up " Group Policy Object Editor ". Here's the picture : Find the group policy as shown in the following figure : Domain found Right click to edit Find the picture below : find [ Computer configuration ...

  5. caffe Add local layer

    download caffe-local, decompression ; modify makefile.config: I am going to cuudn Comment out , Get rid of cpu_only Notes ; make all make test( among local_test error , Jiang Wen ...

  6. Nginx and PHP-FPM Start of 、 restart 、 Stop script sharing ( turn )

    On the server Nginx and PHP Are source code compilation installation , Unlike ubuntu They also have their own service The startup script , So we don't support the previous nginx (start|restart|stop|reload) 了 . Do it yourself ...

  7. python simulation ajax Query social work database ...

    stay windows Use in , Input relevant information to query social work database , It was originally a web version , I put ajax Request extraction . Rough packaging , It's fun . #coding:utf8 import urllib2,urllib from Bea ...

  8. python20151130

    tab Mixing with spaces is an error import os # How to get the current path # The current path can be '.' Express , Reuse os.path.abspath() Convert it to an absolute path print(os.path.abspath('. ...

  9. CodeForce 569A

    Time Limit:2000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u   Description Litt ...

  10. powerDesigner Create classes and data models

    1. Create class diagrams / 2. Create the properties of the class diagram 3. Create a class , This is the corresponding relationship after creation , It can be quoted elsewhere 3. Properties when creating a class name and code Disassociate 4. Create a relationship between two classes Here's a popular science knowledge (ht ...


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved