Import a Module
import sys
sys.path.append("#path#")
path到module的上一层,不要包括module
Use a Module
import a module and use it. hehehehehe
_ __ and __init__
source:https://www.cnblogs.com/coder2012/p/4423356.html
(Oct 13 2018)
'_'
表示private
'__'
避免子类覆盖其内容
a.g.
class A(object):
def __method(self):
print "I'm a method in A"
def method(self):
self.__method() a = A() a.method()
I'm a method in A
class B(A):
def __method(self):
print "I'm a method in B"
b = B()
b.method()
I'm a method in A
__通过改变method的名字使得子类无法修改
'__xx__'
不要调用,用于python调用
class CrazyNumber(object):
def __init__(self, n):
self.n = n
def __add__(self, other):
return self.n - other
def __sub__(self, other):
return self.n + other
def __str__(self):
return str(self.n)
num = CrazyNumber(10)
print num # 10
print num + 5 # 5
print num - 20 # 30
if __name__=='__main__'
source:https://blog.csdn.net/yjk13703623757/article/details/77918633/
(Oct 13 2018)
当.py文件被直接运行时,if __name__=='__main__'之下的代码块将被运行;当.py文件以模块形式被导入时,if __name__ == '__main__'之下的代码块不被运行。
const.py:
PI = 3.14
def main():
print("PI:", PI)
main()
# 运行结果:PI: 3.14
area.py:
from const import PI
def calc_round_area(radius):
return PI * (radius ** 2)
def main():
print("round area: ", calc_round_area(2))
main()
'''
运行结果:
PI: 3.14
round area: 12.56
'''
修改const.py
PI = 3.14
def main():
print("PI:", PI)
if __name__ == "__main__":
main()
运行area.py
round area: 12.56
网友评论