C # program Ape Learning Python

Source: Internet
Author: User

Sun Guangdong 2016.1.1

Interaction:

C # runs Python code:

Http://stackoverflow.com/questions/11779143/run-a-python-script-from-c-sharp

The reverse comes:

Http://stackoverflow.com/questions/3260015/run-a-c-sharp-application-from-python-script


Features of the Python language:
Advanced language
Built-in battery (a large number of standard libraries)
interpreted (sometimes JIT-compiled)
Object-oriented (especially Python 3)
Strongly typed dynamic semantics
Grammar emphasizes readability
Supports reuse through modules and packages

The "shape" of the Python program:
Python defines a block of code ( using spaces and colons in Python).



Look at a Demo:

Import Randomdef get_days ():    # list<string> days = new list<sting> ();    # days[] Days    = [' mon ', ' Tues ', ' Wed ', ' Thurs ', ' Fri ', ' sat ', ' Sun ']    return daysdef get_random_report ():    Weather = [' Sunny ', ' lovely ', ' cold ']    return weather[random.randint (0, Len (weather)-1)]def main (): Days    = Get_d Ays () for Day in days    : report        = Get_random_report ()        print ("on {0} it'll be {1}.") Format (day, report)) If __name__ = = "__main__":    Main ()

What does C # have?


Everything is an object (all objects)

C#:

Class document:object{public    void Serialize ()    {        //...    }    public override string ToString ()    {        return ' I am a document ';    }}

Python:

Class Document (object):    def serialize (self):        print ("Great!") ")    def __str__ (self):        return" I am a document. "


Second, IEnumerable + foreach Loops

C#:

        int[] numbers = new[] {1, 2, 3, 4, 5, 6};        foreach (var n in numbers)        {            Console.Write (n + ",");        }
Class shoppingcart:ienumerable<tuple<string, float>>{    list<tuple<string, float>>  Cartitems = new list<tuple<string, float>> ();    public void Add (string name, float price)    {        cartitems.add (new tuple<string, float> (name, Price));    } Public    ienumerator<tuple<string, float>> GetEnumerator ()    {        return cartitems.getenumerator ();    }    IEnumerator Ienumerable.getenumerator ()    {        return cartitems.getenumerator ();    }}


Python:

numbers = [1, 2, 3, 4, 5, 6]for N in numbers:    print (n, end= ', ') for V in Enumerate (numbers):    print (V, end= ', ') for I Ndex, K in Enumerate (numbers):    print (k, end= ', ')
Class Caritem:    def __init__ (self, Name, price):        self.price = Price        Self.name = name    def __repr__ (self):        return "({0}, ${1})". Format (Self.name, Self.price)class ShoppingCart:    def __init__ (self):        self.__ Items = []    def add (self, cart_item):        self.__items.append (Cart_item)    def __iter__ (self):        return self.__items.__iter__ ()print () print () cart = ShoppingCart () cart.add (Caritem ("CD", 19.99)) Cart.add (Caritem (" Record ", 17.99))) for item in Cart.items:    print (item)



Iii. Properties (int age {get; set;} )

C#:

    Class ShoppingCart    {        list<tuple<string, float>> cartitems = new list<tuple<string, float >> ();        Public float totalprice        {            get            {                float total = 0;                foreach (var item in Cartitems)                {Total                    + = Item. Item2;                }                return total;}}    }

Python:

Class ShoppingCart:    @property    def total_price (self): total        = 0.0 to        item in Self.__items: Total            + = Item.price        return total

Print ("Total Price is ${0:,}". Format (cart.total_price))


Iv. Anonymous types (anonymous type)

C#:

    public static void Main (string[] args)    {        var o = new        {            Id = 2,            registered = True        };        Console.WriteLine (o);        if (o.registered)        {            Console.WriteLine ("They is registered ...");}    }

Python:

Class Anonobject (dict):    __getattr__ = dict.get    __setattr__ = Dict.__setitem__person = {    "name": " Michael ",    " age ": 40}anonperson = anonobject (name =" Michael ", age=40) print (Anonperson) print (anonperson[" name "]) Print (anonperson.name) print (anonperson.age)

Five, Lambda expressions

C#:

    private static ienumerable<int> findnumbers (predicate<int> predicate)    {for        (int i = 0; i <; i+ +)        {            if (predicate (i))            {                yield return i;            }        }    }    Private ienumerable<int> nums = findnumbers (n = n%11 = = 0);    [0, 11,22,33,44,55,66,77,88,99]

Python:

def get_numbers (limit, predicate):    for N in range (0, limit):        if predicate (n):            yield ndef divide_by_ll (n) :    return n = = = 0output = List (Get_numbers (DIVIDE_BY_LL)) print (output)
def get_numbers (limit, predicate):    for N in range (0, limit):        if predicate (n):            yield n# def divide_by_ll (n): #     return n% = = 0output = List (Get_numbers (40,lambda n-==0) print (output)



VI. NuGET Package Management



Vii. Entity Framework "ORMs



Viii. ASP. NET MVC



Ix. LINQ

C#:

        var older = from            p in people             where P.age >            the p.age descending             {age = p.age, name = P . Name}

Python:

Class Person:    def __init__ (self, name, age, Hobby):        self.hobby = hobby        self.name = name        Self.age = Age
   def __repr__ (self):        return ' {0} is {1} and likes {2} '. Format (Self.name, Self.age, Self.hobby) class Anonobject (Dict ):    __getattr__ = dict.get    __setattr__ = dict.__setitem__people = [Person    ("Jeff", "biking"),    Person ("Michael", "Max", "biking"), person ("    saerh", "Running"), Person    ("Tony", "Jogging"    ), Person ("Zoe", "V", "TV"),]bikers = [    anonobject(Name = p.name, pasttime = p.hobby) for    p in PEOPLE
   if P.hobby = = "Biking"]bikers.sort (Key=lambda p:p.name) for B in Bikers:    print (b)


Ten, Iterator Methods/yield return

C#:

    private static ienumerable<int> Fibonaccigenerator ()    {        int current = 1;        int next = 1;        yield return current;        while (true)        {            int temp = current + next;            current = next;            Next = temp;            yield return current;        }    }

Python:

Def fibinnoci (): Current    = 0    NXT = 1    and True: current        , NXT = NXT, current + NXT        #print ("genera Ting "+ str"        yield  currentfor N in Fibinnoci ():    if n > £ º break    print (n, end= ', '    # 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,


Xi. JIT Compilation






??

????????

C # program Ape Learning Python

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.