четверг, 22 октября 2015 г.

Пара годных практик

Instead of writing methods without return values, make them return self

# Instead of this
self.release_water()
self.shutdown()
self.alarm()

class Reactor:
    ...
    def release_water(self):
        self.valve.open()
        return self

self.release_water().shutdown().alarm()   

Enumeration (iteration) method

# Bad
# Can't change type of collection
#     e.g. can't change employees from a list to a set
class Department:
    def __init__(self, *employees):
        self.employees = employees

for employee in department.employees:
    ...
   
# Better
class Department:
    def __init__(self, *employees):
        self._employees = employees

    def __iter__(self):
        return iter(self._employees)

for employee in department:  # More readable, more composable


Оригинал старьи

Комментариев нет:

Отправить комментарий