python基础--结构篇
在C/C++/Java中,main是程序执行的起点,Python中,也有类似的运行机制,但方式却截然不同:
Python使用缩进对齐组织代码的执行,所有没有缩进的代码(非函数定义和类定义),都会在载入时自动执行,这些代码,可以认为是Python的main函数。
每个文件(模块)都可以任意写一些没有缩进的代码,并且在载入时自动执行,为了区分主执行文件还是被调用的文件,Python引入了一个变量__name__,当文件是被调用时,__name__的值为模块名,当文件被执行时,__name__为'__main__'。这个特性,为测试驱动开发提供了极好的支持,我们可以在每个模块中写上测试代码,这些测试代码仅当模块被Python直接执行时才会运行,代码和测试完美的结合在一起。
典型的Python文件结构:
参考:
http://www.cnblogs.com/lvxiuquan/archive/2012/07/09/2582437.html
getter setter方法
class Vehicle: def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity): self.number_of_wheels = number_of_wheels self.type_of_tank = type_of_tank self.seating_capacity = seating_capacity self.maximum_velocity = maximum_velocity @property def number_of_wheels(self): return self._number_of_wheels @number_of_wheels.setter def number_of_wheels(self,numbers): self._number_of_wheels = numbers tesla_model_s = Vehicle(4, 'electric', 5, 250) print(tesla_model_s.number_of_wheels) tesla_model_s.number_of_wheels = 20 print(tesla_model_s.number_of_wheels)
class Vehicle:
def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
self.number_of_wheels = number_of_wheels
self.type_of_tank = type_of_tank
self.seating_capacity = seating_capacity
self.maximum_velocity = maximum_velocity
@property
def number_of_wheels(self):
return self._number_of_wheels
@number_of_wheels.setter
def number_of_wheels(self,numbers):
self._number_of_wheels = numbers
tesla_model_s = Vehicle(4, 'electric', 5, 250)
print(tesla_model_s.number_of_wheels)
tesla_model_s.number_of_wheels = 20
print(tesla_model_s.number_of_wheels)