这场辩论在本质上主要是情境性的,并且将取决于您打算在您的计划中做什么。我要考虑的主要事情是,我是否需要将属性(数据)和功能(方法/函数)封装到一个分组中?
就在这种情况下使用类(对象)的利弊而言,我想到了一些额外的事情:
使用类的原因:
- 如果潜在的未来可维护性将保证将新类“交换”到程序中的现有结构中。
- 如果存在适用于类的所有实例的属性。
- 如果将一组函数与程序的其余部分分开是合乎逻辑的。
- 确保不变性的更简洁选项
- 为基础字段提供类型与您程序的其余部分非常吻合。
不使用类的原因:
- 可以纯粹通过添加新功能来维护代码。
- 您没有对存储的字段执行功能性任务(例如存储
create_date,但只需要使用age - 这可以更好地用于不公开create_date 的对象,而只是一个函数get_age)。
- 您需要满足严格的性能优化标准,并且无法证明调用函数以确保封装、任何额外的内存开销等......
通常,Python 适合使用类,因为它是一种面向对象的语言。但是,与 C++ 和 Java 等更多的 oop 语言相比,您可以在 Python 中“摆脱”更多而不使用类。如果你想探索使用一个类,我当然认为这将是一个很好的语言使用练习。
编辑:
根据后续评论,我想提供一个使用命名参数来实例化具有可选字段的类的示例。一般概述是,Python 在考虑将哪个参数分配给内部功能时解释参数的顺序。举个例子:
def get_info(name, birthday, favorite_color):
age = current_time - birthday
return [name, age, favorite_color]
在此示例中,Python 根据调用方法时输入参数的出现顺序来解释输入参数:
get_info('James', '03-05-1998', 'blue')
然而,Python 也允许命名参数,它明确指定参数内部字段分配:
get_info(name='James', birthday='03-05-1998', favorite_color='blue')
虽然乍一看这种语法似乎更冗长,但它实际上提供了很大的灵活性,因为命名参数的顺序无关紧要,您可以为未传递到方法签名中的参数设置默认值:
def get_info(name, birthday, favorite_color=None):
age = current_time - birthday
return [name, age, favorite_color]
get_info(name='James', birthday='03-05-1998')
下面我提供了一个更深入的工作示例,说明命名参数如何帮助您在评论中概述的情况(许多字段,并非所有字段都需要)尝试以各种方式构造此对象以看看如何需要非命名参数,但命名参数是可选的,并且默认为__init__() 方法中指定的值:
class Car(object):
""" Initializes a new Car object. Requires a color, make, model, horsepower, price, and condition.
Optional parameters include: wheel_size, moon_roof, premium_sound, interior_color, and interior_material."""
def __init__(self, color, make, model, horsepower, price, condition, wheel_size=16, moon_roof=None, premium_sound=None, interior_color='black', interior_material='cloth'):
self.color = color
self.make = make
self.model = model
self.horsepower = horsepower
self.price = price
self.condition = condition
self.wheel_size = wheel_size
self.moon_roof = moon_roof
self.premium_sound = premium_sound
self.interior_color = interior_color
self.interior_material = interior_material
# Prints attributes of the Car class and their associated values in no specific order.
def print_car(self):
fields = []
for key, value in self.__dict__.iteritems():
fields.append(key + ': ')
fields.append(str(value))
fields.append('\n')
print ''.join(fields)
# Executes the main program body
def main():
stock_car = Car('Red', 'Honda', 'NSX', 290, 89000.00, 'New')
stock_car.print_car()
custom_car = Car('Black', 'Mitsubishi', 'Lancer Evolution', 280, 45000.00, 'New', 17, "Tinted Moonroof", "Bose", "Black/Red", "Suede/Leather")
custom_car.print_car()
# Calls main() as the entry point for this program.
if __name__ == '__main__':
main()