Python-01:Python与C# 基本语法区别

350 阅读4分钟

原文来自: Potter个人博客

概要内容

  • Python 与 C# 基本语法区别
  • 具体语法示例

最明显的区别

  1. Python if、for、while等 包裹代码块不是用{},而是使用":"和 换行缩进
  2. Python 弱类型语言,同时每句话结束后无需加分号";",与JAVAScript 类似

具体语法区别:

  • if
C#:
if(条件){
    print("xxx");
}

Python:
if 条件:
    print("xxx")

  • for
C#:
var list = new List<int>(){1, 2, 3};
foreach(n : list)
{
    Console.WriteLine(n);
}

Python:
list = {1, 2, 3}
for n in list:
    print(n)
  • 强制类型转换
C# 
var num = "12";
int n = (int)num

Python
num = "12"
n = int(num)
  • 数组切片: 其实就是copy出数组中的指定区域元素
listnames = ['1','2','3']
listnames[start_index:end_index] 
(注意:copy出来的集合为[start_index,end_index)之前的元素
  • 函数及注释说明
C#:
/// <summary>
/// 测试函数
/// </summary>
public string test(string username)
{
    Console.WriteLine("hello " + username);
    return username;
}

Python:
def test(username):
    """测试函数"""
    print("hello " + username)
    return username.title()
  • 传递任意数量的实参:*实参名
C#:无对应语法

Python
def make_pizza(*toppings): 
    """打印顾客点的所有配料""" 
    print(toppings)

# 任意数量实参, 如果是键值对,请使用**双星号,比如:
def build_profile(first,last,**user_info):
    for key, value in user_info.items(): 
        print("key=" + key + "value=" + value)

注意:任意数量实参只能有一个,并且只能放在函数最后一个参数的位置

  • 模块导入:类似java 在一个类文件中,导入另外一个文件类
C#: 使用userspace 引入空间,既可以直接使用空间中的类
one.cs:内容如下
-------------------------------------------------------------------------
namespace onens 
{
    public class One
    {
    }
}
-------------------------------------------------------------------------
two.cs:内容如下
-------------------------------------------------------------------------
using onens
namespace twons
{
    public class Two
    {
        public Two()
        {
            var one = new One()
        }
    }
}
-------------------------------------------------------------------------
Python: 导出模块后,就可以通过模块名称访问其中的所有方法
OneModule.py:内容如下
-------------------------------------------------------------------------
def one(name, address):
    print(name + "" + address)
-------------------------------------------------------------------------
TwoModule.py:内容如下
-------------------------------------------------------------------------
import OneModule
def two():
    OneModule.one("potter","sz")
-------------------------------------------------------------------------
  • 导入特定函数
C#: 没有导出特定函数一说,只有using namespace的内容 或者说import dll中的方法,比如:
[DllImport("User32.DLL")]
public static extern IntPtr GetActiveWindow();


Python:
from module_name import function_name1,function_name2...
# 使用as给导入函数取别名
from module_name import fuction_name as fn
# 使用as给导入模块取别名
import module_name as mn
# 使用*号,导入模块所有函数
from module_name import *
构造方法
C#: 
class Test
{
    public Test(string name,string address)
    {

    }
}
Python: __init__ 就是构造方法, self是自动传递的
class Test():
    def __init__(self, name, address):
        self.name = name
        self.address = address
    def hello(self):
        print("hello")

  • 继承
C#:
-------------------------------------------------------------------------
class Car
{
    private string make;
    private string model;
    private string year;
    public Car(string make, string model, string year)
    {
        this.make = make;
        this.model = model;
        this.year = year;
    }
    public virtual void Run() 
    {
        Console.WriteLine("run");
    }
}
-------------------------------------------------------------------------
class ElectricCar : Car
{
    private string makeAddress;
    public ElectricCar(string makeAddress, string make, string model ,string year) : base(make, model,year)
    {
        this.makeAddress = makeAddress;
    }
    public override void Run()
    {
        base.Run();
    }
}
-------------------------------------------------------------------------
Python:
-------------------------------------------------------------------------
class Car():
    def __init__(self,make,model,year):
        self.make = make
        self.model = model
        self.year = year
    def run():
        print("run")
-------------------------------------------------------------------------
class ElectricCar(Car):
    def __init__(self,make,model,year):
        super().__init__(make,model,year)
    def run()
        ***子类重写父类方法,同名即可***
        print("ElectricCar run")
-------------------------------------------------------------------------
  • 导入类:(格式:from module_name import class,class)
from car import Car
my_new_car = Car('audi', 'a4', 2016)
  • 文件读写
C#: 
-------------------------------------------------------------------------
1. 读取整个文件
using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    StreamReader sr = new StreamReader(fs);
    strContent = sr.ReadToEnd();
    sr.Close();
    fs.Close();
}
2. 逐行读取文件
using (StreamReader sr = new StreamReader(filepath))
{
    String line;
    while((line=sr.ReadLine())!=null)
    {
        Console.WriteLine(line);
    }
}
3. 写入文件
using (FileStream fs = File.Open(filepath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
    StreamWriter sw = new StreamWriter(fs);
    sw.WriteLine(content);
    sw.Flush();
    sw.Close();
    fs.Close();
}
-------------------------------------------------------------------------
Python:
-------------------------------------------------------------------------
1.读取整个文件,使用rstrip过滤掉前后空格
with open('pi_digits.txt') as file_object: 
    contents = file_object.read() 
    print(contents.rstrip())
2. 逐行读取文件
with open('pi_digits.txt') as file_object: 
    for line in file_object: 
    print(line.rstrip())
3. 写入文件:'w''r''a' 分别代表'写''读''追加'
filename = 'programming.txt' 
with open(filename, 'w') as file_object: 
    file_object.write("I love programming.")
  • 存取数据
C#:其实就是文件写和读
-------------------------------------------------------------------------
Python: 
-------------------------------------------------------------------------
1. 存:
import json 
numbers = [2, 3, 5, 7, 11, 13]
with open(filename, 'w') as f_obj: 
    json.dump(numbers, f_obj)
-------------------------------------------------------------------------
2.import json 
with open(filename, 'r') as f_obj:
    print(json.load(f_obj))
-------------------------------------------------------------------------
  • 异常
C#:
-------------------------------------------------------------------------
int r = 0;
try
{
    r = 5/0
}
catch (Exception e)
{
    Console.WriteLine("出现异常");
}
finally
{
    Console.WriteLine("try最后执行代码");
}
-------------------------------------------------------------------------
Python:
-------------------------------------------------------------------------
try:
    r = 5/0
except ZeroDivisionError:
    raise Exception("抛出异常:除数不能为0")
except FileNotFoundError:
    print("异常打印:文件找不到")
except:
    print("其他异常")
else:
    print("无异常,打印此句")
finally:
    print("最后打印此句")

说明:
1. else 缩进后代码,相当于把这部分代码放到try-except中或者取消缩进放到最后一样,没啥特别的
2. except 不带具体异常,就相当于C#的catch(Exception)
3. raise 相当于C#的throw
-------------------------------------------------------------------------
  • lambda
C#:
格式:(arguments) => { expression };
-------------------------------------------------------------------------
Func<int, int> func = (x) => { return x + 5; };
Console.WriteLine("" + func(5));
-------------------------------------------------------------------------

Python:
格式:lambda arguments : expression
-------------------------------------------------------------------------
func = lambda a : a + 10
print(func(5))
-------------------------------------------------------------------------
  • API
Python: (注意:使用前请使用pip install requests 安装requests模块)
-------------------------------------------------------------------------
import requests
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
response = requests.get(url)
print("Status code:", response.status_code)
# 将API响应存储在一个变量中
response_dict = response.json()
print("Total repositories:", response_dict['total_count'])
# 用完记得关闭,否则下次运行会报:远程主机强迫关闭了一个现有的连接
response.close()
-------------------------------------------------------------------------


以上: 如发现有问题,欢迎留言指出,我及时更正