如何使代码与多个开发人员保持一致?

2024-04-20 02:58:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道Python是一种动态类型化的语言,我可能在这里尝试重新创建Java行为。但是,我有一个团队在这个代码库上工作,我的目标是确保他们以一致的方式做事。我举个例子:

class Company:
    def __init__(self, j):
        self.locations = []

当它们实例化一个公司对象时,会创建一个包含位置的空列表。现在,使用Python,任何东西都可以添加到列表中。但是,我希望此列表仅包含位置对象:

class Location:
    def __init__(self, j):
        self.address = None
        self.city = None
        self.state = None
        self.zip = None

我用类来实现这一点,这样代码就可以自文档化了。换句话说,“位置只有这些属性”。我的目标是他们这样做:

c = Company()
l = Location()
l.city = "New York"
c.locations.append(l)

不幸的是,没有什么能阻止他们简单地做c.locations.append("foo"),也没有什么能告诉他们c.locations应该是位置对象的列表。你知道吗

在与开发人员团队合作时,Pythonic是如何实现一致性的?你知道吗


Tags: 对象代码selfnonecity目标列表init
2条回答

您还可以定义一个新类ListOfLocations,用于进行安全检查。像这样的

class ListOfLocations(list):
   def append(self,l):
      if not isinstance(l, Location): raise TypeError("Location required here")
      else: super().append(l)

OOP解决方案是确保类API的用户不必直接与实例属性交互。你知道吗

方法

一种方法是实现封装添加位置逻辑的方法。你知道吗

示例

class Company:
    def __init__(self, j):
        self.locations = []

    def add_location(self, location):
        if isinstance(location, Location):
            self.locations.append(location)
        else:
            raise TypeError("argument 'location' should be a Location object")

属性

您可以使用的另一个OOP概念是property。属性是为实例属性定义getter和setter的简单方法。你知道吗

示例

假设我们想要为Location.zip属性强制某种格式

class Location:
    def __init__(self):
        self._zip = None

    @property
    def zip(self):
        return self._zip

    @zip.setter
    def zip(self, value):
        if some_condition_on_value:
            self._zip = value
        else:
            raise ValueError('Incorrect format')

    @zip.deleter
    def zip(self):
        self._zip = None

注意,属性Location()._zip仍然是可访问和可写的。下划线表示什么应该是私有属性,nothing is really private in Python。你知道吗

最后一句话

由于Python的高度内省功能,没有什么是完全安全的。你必须和你的团队坐下来讨论你想要采用的工具和实践。你知道吗

Nothing is really private in python. No class or class instance can keep you away from all what's inside (this makes introspection possible and powerful). Python trusts you. It says "hey, if you want to go poking around in dark places, I'm gonna trust that you've got a good reason and you're not making trouble."

After all, we're all consenting adults here.

- Karl Fast

相关问题 更多 >