python 语法
Sharing my notes that I prepared to remember the python syntax from already known language syntax. (Swift 4.2; Python 3.7)
分享我准备记住的已知语法中的python语法的注释。 (快速4.2; Python 3.7)
“The Loci method is one of the most ancient memorization tools known, and is based on attaching individual items you need to remember, to individual points on a route you are familiar with, so you can easily recall the items as you “walk” that route in your mind.”
“ 基因座方法是已知的最古老的记忆工具之一,它基于将您需要记住的单个项目附加到您熟悉的路线上的各个点上,因此您可以在“行走”时轻松回忆这些项目。在你的脑海中前进。”
Basics 基本 Collection Types 集合类型 Class, Struct 类,结构 Closures 关闭 Exception Handling 异常处理 Unit Testing 单元测试Swift
Swift
import Foundationtypealias a module
类型别名模块
typealias SMSomeStruct = SomeModule.SomeStructImport only parts from a module
仅从模块导入零件
import struct SomeModule.SomeStructimport class SomeModule.SomeClassimport func SomeModule.someFuncPython
Python
import calculatortypealias a module
类型别名模块
import calculator as calcImport only parts from a module
仅从模块导入零件
from calculator import multiply# usageresult = multiply(2, 4)Swift
Swift
let maximumHeight = 50Python
Python
Create constant.py file (global file)
创建constant.py文件(全局文件)
PI = 3.14GRAVITY = 9.8MAXIMUM_HEIGHT = 50Usage:
用法:
import constantconstant.MAXIMUM_HEIGHTSwift
Swift
var userName = "Sit Bibendum"userName = "Malesuada Mollis"Python
Python
userName = "Sit Bibendum"userName = "Malesuada Mollis"# Assigning multiple values to multiple variablesa, b, c = 5, 3.2, "Hello"# to assign the same value to multiple variables at oncex = y = z = 1000Swift
Swift
// single comment/* multi line comment */Python
Python
# python comment, no multiline commentSwift
Swift
let id = 525let name = "Porta Tortor"print(id, name) // 525 Porta Tortorprint(id, name, separator: ", ") // 525, Porta TortorPython
Python
id = 525name = "Porta Tortor"print(id, name) # 525 Porta Tortorprint(id, name, sep=', ') # 525, Porta TortorSwift
Swift
for i in 1 ..< 10 { print(i, terminator: " ") if i % 3 == 0 { print() }}output: 1 2 3 4 5 6 7 8 9Python
Python
for i in range(1, 10): print(i, end=' ') if i % 3 == 0: print()output: 1 2 3 4 5 6 7 8 9Swift
Swift
let html ="""<html> <body> </body></html>"""Python
Python
html = """<html> <body> </body></html>"""(or) using single quotes
(或)使用单引号
html2 = '''<html> <body> </body></html>'''Swift
Swift
let id = 525let name = "Porta Tortor"let msg = "\(id): \(name)" // 525: Porta TortorPython
Python
id = 525name = "Porta Tortor"msg = "%d: %s" % (id, name) # 525: Porta Tortormsg = "{}: {}".format(id, name) # 525: Porta Tortormsg = "{0}: {1}".format(id, name) # 525: Porta TortorSwift
Swift
let userID = 525let firstName = "Cursus"let lastName = "Dolor"let text = firstName + " " + lastName + " (" + String(userID) + ")."output:Python
Python
userID = 525firstName = "Cursus"lastName = "Dolor"text = firstName + " " + lastName + " (" + str(userID) + ")."output:Swift
Swift
let height = 5.7type(of: height) // Double.Typeif height is Int { // ..}Python
Python
height = 5.7type(height) # <type 'float'>if (type(height) is float): # ..Swift
Swift
let userIDString = "525"let userID = Int(userIDString)Python
Python
user_id_string = "525"user_id = int(user_id_string)Swift
Swift
let binary = "11001"let number = Int(binary, radix: 2) // 25Python
Python
binary = "11001"number = int(binary,2) // 25Swift
Swift
var isEnabled = true // falsePython
Python
isEnabled = True # FalseSwift
Swift
let http404Error = (404, "Not Found")let code = http404Error.0let message = http404Error.1// orlet (statusCode, statusMessage) = http404ErrorPython
Python
http404Error = (404, "Not Found")code = http404Error[0]message = http404Error[1]Swift
Swift
var email: String? = nilPython
Python
email = NoneSwift
Swift
// ??Python
Python
name = Mattis Ridiculusdel name # object will be deleted completlyprint(name) # NameError: "name 'name' is not defined"Swift
Swift
var email: String? = nil// Optional wrapif let email = email { print(email)} else { print("n/a") }// Force unwrapif email != nil { print(email!)} else { print("n/a")}Output: n/aPython
Python
email = Noneif email is not None: print(email)else: print("n/a")or
要么
if email != None: print(email)else: print("n/a")Output: n/aSwift
Swift
if self.x == other.x && self.y == other.y { return true} else { return false}Python
Python
if (self.x == other.x and self.y == other.y): return Trueelse: return FalseSwift
Swift
let text = "one\ntwo\nthree"let regExp = "Language: \"Swift\", version: \"4.2\""Python
Python
text = "one\ntwo\nthree"regExp = "Language: \"Python\", version: \"3.7\""# one two three#Swift
Swift
let text = "abc 123"text.count // 7Python
Python
text = "abc 123"len(text) # 7Swift
Swift
enum Color: Int { case red = 1 case green case blue var name: String { switch self { case .red: return "red" case .green: return "green" case .blue: return "blue" } }}// Usage:Color.greenColor.green.nameColor.green.rawValuelet selectedColor = Color.greenif case Color.green = selectedColor { print("Selected right color")} else { print("Wrong color selected \(selectedColor.name)")}Python
Python
from enum import Enumclass Color(Enum): red = 1 green = 2 blue = 3Color.green # Color.greenColor.green.name # greenColor.green.value # 2# Usage:selectedColor = Color.greenif selectedColor is Color.green: print("Selected Right color")else: print("Wrong color selected: {}".format(selectedColor.name))Swift
Swift
switch input { case 0: //.. case 1: break case 2: //..}Python
Python
python does not have any switch case statement. Alternatively we use dictionary mapping.Swift
Swift
func swapInts(a: inout Int, b: inout Int) { let temp = a a = b b = temp}var a = 50var b = 100swapInts(a: &a, b: &b)print(a, b)Python
Python
There are no variables in Python. There are names and objects in - Python and together they appear like variablesSwift
Swift
// TODO: ??Python
Python
def validateInputs(input_function): def validation(a, b): if b == 0: print("Can't divide by 0") return return input_function(a, b) # call input function return validation@validateInputsdef div(a, b): return a / bdiv(10,0)# need to check how to achieve Decorator Pattern using python decorators. (ie.. without modifying the source code file)Swift
Swift
// achieve using closuresfunc makeIncrementer(_ amount: Int) -> () -> Int { var runningTotal = 0 func incrementer() -> Int { runningTotal += amount return runningTotal } return incrementer}let incrementByTen = makeIncrementer(10)incrementByTen()incrementByTen()for _ in 0..<10 { print(incrementByTen())}Python
Python
def makeIncrementer(amount): runningTotal = 0 while True: runningTotal += amountyield runningTotalincrementerByTen = makeIncrementer(10)next(incrementerByTen) # 10next(incrementerByTen) # 20for i in range(10): print(next(incrementerByTen)) # 30 40 ... 120Swift
Swift
var hetro: [Any] = ["one", 10, 2.5]hetro[0]// Negative Indexing not allowedhetro[1] = "100"hetro.remove(at: 0)hetro.append("five")hetro.append(4.9)hetro.append("five")// No inbuilt method to remove an element directlyhetro.insert(10000, at: 1)Python
Python
hetro = ["one", 10, 2.5]hetro[0] # one# reverse indexhetro[-1] # 2.5hetro[-2] # 10hetro[1] = "100"# pop at indexhetro.pop(0)# appendhetro.append("five") hetro.append(4.9)hetro.append("five")# remove first occuranceshetro.remove("five")# insert at indexhetro.insert(1, "100000")Swift
Swift
var list = [Any]()Python
Python
list = []Swift
Swift
let matrix = [[1,2,3], [4,5,6], [7,8,9]]matrix[0][0]matrix[2][2]Python
Python
matrix = [[1,2,3], [4,5,6], [7,8,9]]matrix[0][0] matrix[2][2]Swift
Swift
let list = ["zero", "one", "two", "three", "four"]list.countPython
Python
list = ["zero", "one", "two", "three", "four"]len(list)Swift
Swift
let list = ["zero", "one", "two", "three", "four"]list[1...4]list[..<2]list[2...]Python
Python
list = ["zero", "one", "two", "three", "four"]list[1:4] # ['one', 'two', 'three']list[ :2] # ['zero', 'one']list[2: ] # ['two', 'three', 'four']list[start: end-1] understanding-pythons-slice-notation
list [start:end-1] 理解-pythons-slice-notation
Swift
Swift
var countArray = Array(repeating: 0, count: 10) // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]Python
Python
countArray = [0] * 10# orcountArray = [0 for i in range(10)] # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]Swift
Swift
var basket: Set = ["one", "two", "three"]let isExists = basket.contains("one")basket.insert("four")basket.update(with: "four") // if aleady contains will return `input`; else returns nil;// there is no inbuild method for appending listbasket.remove("four")basket.popFirst()basket.removeAll()Python
Python
basket = { "one", "two", "three"}# orbasket = set({ "one", "two", "three"})isExists = "one" in basketbasket.add("four")basket.update(["five", "six"])basket.remove("six")basket.discard("six") # If the item to remove does not exist, discard() will NOT raise an error.# take random elementrandom = basket.pop() # threebasket.clear() # set([])Swift
Swift
var basket = Set<AnyHashable>() // Set([])Python
Python
basket = set() # set([])Swift
Swift
var info:[String: Any] = [ "name": "Elit Vestibulum", "age": 43]let name = info["name"]info["age"] = 54info["country"] = "Cursus Elit"info.updateValue("Nibh Dapibus", forKey: "city")info.valuesinfo.keysinfo.removeValue(forKey: "age")info.removeAll()Python
Python
info = { "name" : "Elit Vestibulum", "age": 43}# get name = info["name"] name = info.get("name")# updateinfo["age"] = 54# add new pairsinfo["country"] = "Cursus Elit"info.update({"city": "Nibh Dapibus"}) # get all valuesvalues = info.values() # get all keyskeys = info.keys()# remove pairinfo.pop("age")info.clear() # {}Swift
Swift
var info = [String: Any]() // [:]Python
Python
info = dict() # {}Swift
Swift
class MyClass { init() { print("Hello World") }}let myObject = MyClass()Python
Python
class MyClass: def __init__(self): print("Hello World")myObject = MyClass()Swift
Swift
class Math { let pi = 3.14 func areaOfCircle(radius r: Double) -> Double { return pi * (r * r) } func sum(a: Int, b: Int) -> Int { return a + b }}let math = Math()let area = math.areaOfCircle(radius: 10)let sum = math.sum(a: 5, b: 2)Python
Python
class Math: pi = 3.14 # default initializer; to access `self` is required (ie. self.pi) def areaOfCircle(self, radius: float) -> float: return self.pi * (radius * radius) def sum(self, a, b): return a + b # Function annotations are completely optional metadata information about the types used by user-defined functions def substract(self, a: int, b: int) -> int: return a - bmath = Math()area = math.areaOfCircle(10) # 314.0sum = math.sum(2, 5) # 7result = math.substract(2, 5) # -3Swift
Swift
class Table { let multipler: Int init(input: Int) { self.multipler = input } func printTable(limit: Int = 10) { for i in 1 ... limit { print("\(multipler) * \(i) = \(i * multipler)") } print() }}let table2 = Table(input: 2)table2.printTable()table2.printTable(limit: 5)Python
Python
class Table: def __init__(self, input): self.multipler = input def printTable(self, limit = 10): for i in range(1, limit): print("%d * %d = %d" % (self.multipler, i, self.multipler * i)) print()table_2 = Table(2)table_2.printTable()table_2.printTable(5)output:2 * 1 = 2 ..... 2 * 9 = 182 * 1 = 2 2 * 2 = 4 2 * 3 = 6 2 * 4 = 8Swift
Swift
class Employee { let id: Int let name: String init(id: Int, name: String) { self.id = id self.name = name } func printDetails() { print("id: \(id)") print("name: \(name)") }}class Technician: Employee { let labId: String init(id: Int, name: String, labId: String) { self.labId = labId super.init(id: id, name: name) } override func printDetails() { super.printDetails() print("labId: \(labId)") }}let technician = Technician(id:Python
Python
class Employee: def __init__(self, id, name): self.id = id self.name = name def printDetails(self): print("id: %s" % (self.id)) print("name: %s" % (self.name))class Technician(Employee): def __init__(self, id, name, labID): self.labID = labID super().__init__(id, name) # Override method def printDetails(self): super().printDetails() print("labID: %s" % (self.labID))technician = Technician(2693, "Nibh Fringilla", "LAB001")professor.printDetails()output:id: 2693 name: Nibh Fringilla labID: LAB001Swift
Swift
class Hacker { private var name = "Amet Lorem" private func details() { print(name) } func publicDetails() { print("random name") }}let hacker = Hacker()hacker.publicDetails() // random namePython
Python
class Hacker: __name = "Amet Lorem" def __details(self): print(self.__name) def publicDetails(self): print("random name")hacker = Hacker()hacker.publicDetails() # random name# "'Hacker' object has no attribute '..'" -- error for below commandshacker.namehacker.__namehacker.details()hacker.__details()Swift
Swift
struct Center { let x: Float let y: Float}// Equatable ~= __eq__// Hashable ~= __hash__// CustomStringConvertible ~= __repr__Python
Python
from dataclasses import dataclass@dataclassclass Center: x: float y: floatc1 = Center(4,5)print(c1) # Center(x=4, y=5)Adventage of Data Classses: Auto generated _init_, _repr_, _eq_, ..
数据类的出现:自动生成的_ init _ ,_ repr _ ,_ eq _ ,..
ref: https://medium.com/mindorks/understanding-python-dataclasses-part-1-c3ccd4355c34
参考: https : //medium.com/mindorks/understanding-python-dataclasses-part-1-c3ccd4355c34
@dataclass(frozen = True) # immutable# To control the auto generated methods@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)same functionality using class:
使用类的相同功能:
class Center: def __init__(self, x, y): self.x = x self.y = y def __eq__(self, other): if (self.x == other.x and self.y == other.y): return True else: return False def __repr__(self): return 'Point(x=%s, y=%s)' % (self.x, self.y) # .. have to implement all functions manuallySwift
Swift
var addTen = { $0 + 10 }addTen(5) # 15Python
Python
lambda arguments: expression
lambda参数:表达式
Note: Only one expression (a + 10) is allowed with lambda functions.
注意: lambda函数只允许使用 一个表达式( a + 10 ) 。
addTen = lambda a: a + 10addTen(5) # 15# or use `def` if cannot achieve in single expressiondef addTen(a): .. .. return a + 10Swift
Swift
var product: ((Int, Int) -> (Int)) = { a, b in return a * b}product(5, 10)Python
Python
product = lambda a, b: a * bproduct(5, 10) # 50Swift
Swift
func makeNTimes(_ n: Int) -> ((Int) -> Int) { return { a in return a * n }}var doubler = makeNTimes(2)doubler(10)var tripler = makeNTimes(3)tripler(10)Python
Python
def makeNTimes(n): return lambda a: a * ndoubler = makeNTimes(2)doubler(10) # 20tripler = makeNTimes(3)tripler(10) # 30Swift
Swift
let numbers = [1, 2, 3, 4, 5]let result = numbers.map { $0 * 2 }Python
Python
map(function, iterables)
地图(函数,可迭代)
numbers = [1, 2, 3, 4, 5]multiply2 = lambda x: x * 2result = list(map(multiply2, numbers)) # orresult = list(map(lambda x: x * 2, [1, 2, 3, 4, 5]))output:[2, 4, 6, 8, 10]Swift
Swift
let numbers = [1, 2, 3, 4, 5, 6]let result = numbers.filter { $0 % 2 == 0 }Python
Python
filter(function, iterable)
过滤器(功能,可迭代)
numbers = [1, 2, 3, 4, 5, 6]result = list(filter(lambda x : x % 2 == 0, numbers)) # [2, 4, 6]Swift
Swift
let numbers = [1, 2, 3, 4, 5, 6]let res = numbers.reduce(1) { (result, value) -> Int in return result * value}Python
Python
reduce(function, iterable)
减少(功能,迭代)
from functools import reducenumbers = exp = lambda x: x * 2product = reduce(exp, numbers) # 720Swift
Swift
enum InputValidationError: Error { case invalidInput(String)}func validateAge(_ age: Int) throws { if age < 0 { throw InputValidationError.invalidInput("Only positive integers are allowed") }}do { try validateAge(-2)} catch InputValidationError.invalidInput(let message) { print("Exception: ", message)}Python
Python
class InputValidationError(Exception): def __init__(self, message): self.message = messagedef validateAge(age): if age < 0: raise InputValidationError('Only positive integers are allowed')try: validateAge(-1)except InputValidationError as error: print("Exception: ", error.message)except: print("something is wrong")Swift
Swift
enum CommonError: Error { case divisionByZero}func divide(_ a: Int, by b: Int) throws -> Int { if b == 0 { throw CommonError.divisionByZero } return a / b}var result: Intdo { result = try divide(10, by: 0)} catch CommonError.divisionByZero { print("division by zero!")} catch { //}Note: - In Swift there is no functionality to catch arbitrary runtime errors.- no `finally`make use of `defer`Python
Python
def divide(x, y): try: result = x / y except ZeroDivisionError: print("division by zero!") else: print("result is ", result) finally: print(".. executing finally")>> divide(2, 1)output:result is 2.0.. executing finally>> divide(2, 0)division by zero!.. executing finallySwift
Swift
import XCTest@testable import AppTargetclass AppHelperTests: XCTestCase { let calculator = Calculator() override func setUp() { super.setUp() // .. } override func tearDown() { // .. super.tearDown() } func testAdd() { let result = calculator.add(2, 3) XCTAssertEqual(result, 5) } func testMultiply() { let result = calculator.multiply(2, 3) XCTAssertEqual(result, 6) }}Python
Python
calculator.py
计算器
def add(a, b): return a + bdef multiply(a, b): return a * bimport unittestimport calculatorclass TestCalculator(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_add(self): result = calculator.add(2, 3) self.assertEqual(result, 5) def test_multiply(self): result = calculator.multiply(2, 3) self.assertEqual(result, 6)Running Tests
运行测试
if __name__ == '__main__': unittest.main()# Console output:..--------------------------------------------------------------------Ran 2 tests in 0.000sOKpass Statement:
通过声明:
used when a statement is required syntactically but you do not want any command or code to execute.
在语法上需要语句但您不希望执行任何命令或代码时使用。
List of assets: ref: https://docs.python.org/2/library/unittest.html
资产列表:参考: https : //docs.python.org/2/library/unittest.html
Corrections are welcome :). Thank You.
欢迎更正:)。 谢谢。
翻译自: https://medium.com/@kiran.sarella/syntax-comparison-swift-vs-python-5a3d6231d0fe
python 语法