zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C#程序猿学习 Python

2023-09-27 14:23:29 时间

孙广东  2016.1.1

交互:

C# 运行Python代码:

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

反着来:

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


Python语言的特点:
高级语言
内置电池(大量的标准库)
解释型(有时JIT编译)
面向对象(尤其是Python 3)
强类型动态语义
语法强调可读性
支持重用通过模块和包

Python程序的“形状” :
    Python定义代码块(在Python中使用 空格 和 冒号)。



看一个 Demo:

import random

def get_days():
    # List<string> days = new List<sting>();
    # days[]
    days = ['mon','tues','wed','thurs','fri','sat','sun']
    return days

def get_random_report():
    weather = ['sunny', 'lovely','cold']
    return weather[ random.randint(0, len(weather) - 1)]

def main():
    days = get_days()

    for day in days:
        report = get_random_report()
        print("On {0} it will be {1}.".format(day, report))

if __name__ == "__main__":
    main()

C# 都有什么呢?


一、 Everything is an object (一切皆对象)

C# :

class Document: object
{
    public void Serialize()
    {
        // ...
    }

    public override string ToString()
    {
        return "I am a document ";
    }
}

Python:

class Document(object):
    def serialize(self):
        print("太好了!")

    def __str__(self):
        return "I am a document."


二、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 index, 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)



三、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
        for item in self.__items:
            total += item.price
        return total

print("Total price is ${0:,}".format(cart.total_price))


四、Anonymous types (匿名类型)

C#:

    public static void Main(String[] args)
    {
        var o = new
        {
            Id = 2,
            Registered = true
        };

        Console.WriteLine(o);

        if (o.Registered)
        {
            Console.WriteLine("They are 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)

五、Lambda expressions

C#:

    private static IEnumerable<int> FindNumbers(Predicate<int> predicate)
    {
        for (int i = 0; i < 100; 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 n

def divide_by_ll(n):
    return n % 11 == 0

output = list(get_numbers(40, 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 % 11 == 0

output = list(get_numbers(40,lambda n : n % 11 ==0 ))
print(output)



六、NuGET package management



七、Entity Framework 》ORMs



八、ASP.NET MVC



九、LINQ

C# :

        var older =
            from p in people 
            where p.age > 30
            orderby p.age descending 
            select new { 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", 50, "Biking"),
    Person("Michael", 40, "Biking"),
    Person("Saerh", 30, "Running"),
    Person("Tony", 24, "Jogging"),
    Person("Zoe", 12, "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)


十、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

    while True:
        current, nxt = nxt, current + nxt
        #print("Generating" + str(current))
        yield  current

for n in fibinnoci():
    if n > 200:
        break

    print(n, end=', ')
    # 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,


十一、JIT compilation