C#程序员学习 Python

unity3d Editor私人定制 专栏收录该内容
158 篇文章 3 订阅

孙广东  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