孙广东  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 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_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 = priceself.name = namedef __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:
    @propertydef total_price(self):total = 0.0for item in self.__items:total += item.pricereturn 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 ndef divide_by_ll(n):return n % 11 == 0output = 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 == 0output = 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 > 30orderby p.age descending select new { age = p.age, name = p.name }

python:

class Person:def __init__(self, name, age, hobby):self.hobby = hobbyself.name = nameself.age = agedef __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 peopleif 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 = 0nxt = 1while True:current, nxt = nxt, current + nxt#print("Generating" + str(current))yield  currentfor n in fibinnoci():if n > 200:breakprint(n, end=', ')# 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,

十一、JIT compilation








C#程序员学习 Python相关推荐

  1. java min 函数的使用方法_【Python】Java程序员学习Python(五)— 函数的定义和使用...

    不想做一个待宰的羔羊!!!!要自己变得强大.... 函数的定义和使用放在最前边还是有原因的,现在语言趋于通用,基本类型基本都是那些,重点还是学习对象的使用方法,而最根本的还是方法的使用,因此优先介绍, ...

  2. python按键暂停程序_汇总程序员学习python必备的42个快捷键,看完收获满满

    很多程序员在学习python的时候,是否遇到过一些操作不方便且很繁琐小问题,特别还会影响到你工作的进度,或许这50个快捷键能够帮助到你哦! 首先先从Shift系列的按键开始: 1. Shift+Alt ...

  3. python好学吗 老程序员-学习python,难道是为了当一名苦逼的程序员吗?

    最近在和朋友聊天的时候,朋友问了我这样一个问题,问我:你报培训班学习python有用吗?听说程序员虽然工资高,但是工作强度很大,天天加班而且还会遇到中年危机,不像律师,会计这种越老越挣钱.当我听完后, ...

  4. 有python基础学习java简单吗_【Python】Java程序员学习Python(三)— 基础入门

    一闪一闪亮晶晶,满天都是小星星,挂在天上放光明,好像许多小眼睛.不要问我为什么喜欢这首歌,我不会告诉你是因为有人用口琴吹给我听. 一.Python学习文档与资料 一般来说文档的资料总是最权威,最全面的 ...

  5. python的类程序的结构_Python程序员学习路径之数据结构篇

    原标题:Python程序员学习路径之数据结构篇 点击标题下「异步图书」可快速关注 在计算机科学中,数据结构是一门进阶性课程,概念抽象,难度较大.Python语言的语法简单,交互性强.用Python来讲 ...

  6. python后端开发学路线_【后端开发】Python要学哪些内容?Python程序员学习路线图...

    很多零基础入门学习python不知道学习什么?也不知道Python要学哪些内容?下ki4网为您总结一下Python程序员学习路线图. python的应用范围是很广泛的,例如一些网络的爬虫,和web的开 ...

  7. python程序员培训_Python程序员学习路线图

    Python程序员学习路线图,由黄哥python培训授课老师黄哥所写. 参加黄哥python远程视频培训, 帮你完成从不会写代码到会写代码解决问题的过渡. 咨询qq:1465376564 Python ...

  8. python程度员要学很多英语吗_谈谈程序员学习英文

    今天把<Ogre 3D 1.7 Beginner's Guide>看完了,这也是我第一次完整的阅读完一本英文书籍,当然也是第一本英文技术书籍.来和大家分享一下我对程序员学习英文的一些看法. ...

  9. 30岁自学python找工作-程序员自学Python开发,20到30岁几乎决定了你的未来!

    原标题:程序员自学Python开发,20到30岁几乎决定了你的未来! 之前程序员界流行一句话:人生苦短,请用Python. 随着Python成为网红语言之后,不少程序员想多学这一门语言好傍身. 甚至有 ...

最新文章

  1. 盛大文学难逃“垄断”嫌疑,完美文学虎口夺食
  2. php httpclient.class.php,php实现httpclient类示例
  3. Necessary configuration to get Smart business tile work in UXT/928
  4. oracle重新编译package,如何有效的编译数据库中的失效对象(Package,trigger等)
  5. 嵌入式常见笔试题总结(6)
  6. H5 输入框text和number切换
  7. 1389. 按既定顺序创建目标数组
  8. IMAP与POP3的比较
  9. linux tomcat守护_Linux 系统下 Tomcat 的服务配置和性能优化
  10. tensorflow 实验过程可重复
  11. Python中面向对象初识到进阶
  12. User-Agent 汇总
  13. 基于matlab的暴雨强度公式参数推求,基于MATLAB的暴雨强度公式参数推求
  14. 基于OpenVINO的端到端DL网络-初步接触OpenVINO提供的例子(win+vs)
  15. 2022版首发,阿里Java开发手册(黄山版).PDF
  16. 陪你看这世间---识人术
  17. 冰冻三尺非一日之寒——大型网站架构演进
  18. linux如何上传数据到百度网盘,Linux命令行上传文件到百度网盘
  19. JavaFx界面设计【SceneBuilder版】适合初学者
  20. 2020年 Top 6+ 最佳免费字体网站

热门文章

  1. 移动端布局(三) rem布局及原理
  2. 基于STM32F103单片机智能风扇 手机蓝牙无线控制系统
  3. 物联网·暖通空调远程在线监控控制系统
  4. 三岔口,视频网站的侥幸与不幸
  5. js中mache和replace的用法区别
  6. Codeforces Round #827 (Div. 4)(A-G)
  7. 汉王人脸考勤七剑齐发 技术领先国际
  8. 软件测试(软件测试生命周期,描述一个bug,定义bug级别,bug生命周期,如何开始第一次测试,测试执行和bug管理,测试工作中的人际关系处理)
  9. 服务器安装centos系统报错/dev/root/does not exist
  10. echarts 柱状图圆柱_ECharts象形柱图