返回信息流美丽胜于丑陋
# python
a,b = b,a
// c
#define swap(x,y) do \
{ unsigned char swap_temp[sizeof(x) == sizeof(y) ? (signed)sizeof(x) : -1]; \
memcpy(swap_temp,&y,sizeof(x)); \
memcpy(&y,&x, sizeof(x)); \
memcpy(&x,swap_temp,sizeof(x)); \
} while(0)
显式胜于隐式
# python
n = 42
print(str(n) + "is the truth.")
m = "90"
m_plus_one = int(m) + 1
// JavaScript
var n = 42;
alert("" + n + "is the truth.");
var m = "90";
var m_plus_one = (+m) + 1; // "positive m" converts!
简单胜于复杂
# python
v = 2**100
// java
BigInteger v = BigInteger.valueOf(2L).pow(100); // why the power is a small integer?
复杂胜于繁琐
# python
items = [1,2,3,4,5,6,7,8,9,10]
result = ",".join(str(i*2) for i in items if i%2 == 0)
// java
int[] items = {1,2,3,4,5,6,7,8,9,10};
StringBuilder sb = new StringBuilder();
boolean first = true;
for (int i in items) {
if (i % 2 == 0) {
int j = i * 2;
if (first) {
sb.append(j);
first = false;
} else {
sb.append(",");
sb.append(j);
}
}
}
String result = sb.toString();
可读性很重要
# python
print("Hello Python")
# perl
$_="krJhruaesrltre c a cnP,ohet";$_.=$1,print$2while s/(..)(.)//;
平板胜于嵌套
# python
from sqlite3 import Connection
...
// java
import org.springframework.jdbc.core.JdbcTemplate;
特殊情况不论多么特殊,也不应该破坏规则:
// python
a = -2147483648
b = -1
c = a // b # 2147483648
d = None
def foo(): # no parameter
pass
// c, assume x86_64+Linux where int is 32-bit.
int a = -2147483648;
int b = -1;
int c = a%b; // Killed by SIGFPE
int *d = (void*)0; // casting int to ptr has implementation-defined behaviour, but this one is special. It is defined as NULL.
void *e = nullptr; // good if you are using c++11;
void foo(void) { // foo() means "any parameters" in C, not "no parameter".
}
即使实践优先于纯粹性,错误也不应该悄悄地被忽略,除非被显式地抑制。
# python
d = {1:"a", 2:"b"}
x = d[3] # KeyError
y = d.get(3, None) # None
// java
Map<Integer, String> d = new HashMap<Integer, String>();
d.put(1, "a");
d.put(2, "b");
String x = d.get(3); // null;
// scala. Similar to Python, but static.
val d = Map(1->"a", 2->"b")
val x: String = d(3) // NoSuchElementException
val y: Option[String] = d.get(3) // None
val z: Option[String] = d.get(2) // Some("b")
面对歧义,请抵制猜想的诱惑
# python
if foo:
if bar:
foo_and_bar()
else:
foo_but_not_bar()
if foo:
if bar:
foo_and_bar()
else:
not_foo_dont_care_about_bar()
// c, c++, java
if(foo)
if(bar)
foo_and_bar();
else
what_is_this(); // actually foo_but_not_bar
一件事应该有唯一而且明确的方法来做
# python
l = get_a_list()
if len(l) == 0:
do_something()
# perl
my @l = .....
if(@l) { ... }
if(@l==0) { ... } # are they really "equal"?
if($#l < 0) { ... } # why < 0?
这是一条镜像帖。来源:北邮人论坛 / python / #5803同步于 2015/3/25
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Python机器人发帖
Python是我最喜欢的语言之一
nuanyangyang
2015/3/25镜像同步115 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复