python中的main()只是一个函数名。俗语if __name__ == '__main__':
#do something
是一个快捷方式,用于确定此文件中的代码正在作为程序运行,而不是作为模块导入。在
因为python的目的是不使用类型,所以社区非常强调约定和最佳实践。这并不能提供与编译器相同级别的可预测性,但它有助于避免混乱。可读性是python的核心价值,类似这样的习惯用法提供了有价值的结构。在
Python不像其他语言那样支持函数重载。在强类型语言中,可以用相同的名称编写同一函数的多个版本,但输入参数不同:
^{pr2}$
在python中没有对等的习惯用法。在大多数情况下,这是不必要的:对于一个数值运算,你并不真正关心传入的数字是浮点、整数还是其他什么,只是它们支持正确的运算符。这就是python的咒语“duck typing”的由来——如果它走路像鸭子,嘎嘎叫得像鸭子,那就是鸭子。所以python的函数是惯用的look for functions or operators on incoming arguments rather than checking their types。在
例如实例与静态方法:
在python中,每个实例方法都隐式地将所属实例作为函数的第一个参数:class Test(object):
def __init__(self, arg):
= arg
def example(self):
fred = Test(999) # note: no 'self' passed here
()
>>> 999
joe = Test(-1)
()
>>> -1
类方法获取类类型而不是实例作为隐式第一个参数。类方法可以看到类级别的变量,这些变量是在类范围内定义的,而不是在实例范围内定义的,但它们对特定实例一无所知。在class TestCls (Test)
CLASS_VARIABLE = "hello"
# other behavior inherited from Test
@classmethod
def class_example(cls):
print cls.CLASS_VARIABLE
barney = TestCls(123)
()
>>> 123
barney.class_example() # again, no explicit class passed in
>>> 'hello'
静态方法根本没有隐式参数:class TestStatic (TestCls):
CLASS_VARIABLE = 'goodbye'
# inherited stuff again
@staticmethod
def static_test():
print "behold, I have no implicit argument"
静态方法和类方法也不需要调用实例:wilma = TestStatic(123)
wilma.static_test() # you can call from an instance
>>> behold, I have no implicit argument
# or not:
TestStatic.static_test()
>>> behold, I have no implicit argument
TestStatic.class_example()
>>> goodbye # the method is inherited, but the class variable come from this class