【问题标题】:How to return a value from a method back to the input value [closed]如何将方法中的值返回到输入值[关闭]
【发布时间】:2015-08-19 13:59:19
【问题描述】:

我创建了一个辅助方法来检查一个国家/地区的邮政编码格式。因为我有多个邮政编码(例如访问、邮政),所以我想使用这个辅助方法。 当我调试时,我可以看到 self.zip 被放入值 zipcode 中,但是当它通过方法 zipcode 运行时会按应有的方式更新,但它不会将值返回给 self.zip。

有人可以向我解释我怎样才能让它工作吗?

def onchange_zip(self):
    self.postal_code_format(self.zip, self.country_id)

def postal_code_format(self, zipcode, country):
    if country.name == "Netherlands":
        zipcode = zipcode.replace(" ", "").upper()
        if len(zipcode) == 6:
            numbers = zipcode[:4]
            letters = zipcode[-2:]
            if letters.isalpha() and numbers.isdigit():
                zipcode = str("{0} {1}").format(numbers, letters)
            else:
                raise ValueError("Could not properly format the postal code.")
        else:
            raise ValueError("Could not properly format the postal code.")
        return zipcode

【问题讨论】:

标签: python python-2.7 methods return-value


【解决方案1】:

当你说

zipcode = zipcode.replace(" ", "").upper()

您正在使zipcode 引用一个新的字符串对象。它不再引用self.zip 对象。

这样做的正确方法是像这样将值分配回self.zip

self.zip = self.postal_code_format(self.zip, self.country_id)

或者在postal_code_format函数本身中重新赋值,而不是像这样返回

self.zip = zipcode

注意:字符串对象无论如何都是不可变的。这意味着,对字符串对象的任何操作都会给你一个新的字符串对象,它们不会修改原始对象。例如,

>>> string_obj = 'thefourtheye'
>>> string_obj.upper()
'THEFOURTHEYE'
>>> string_obj
'thefourtheye'

正如您在此处看到的,string_obj.upper() 返回一个全大写字母的新字符串对象,但原始对象保持不变。所以你不能改变self.zip的值。

【讨论】:

  • 感谢 thefourtheye 的快速回复。因此,如果我做对了,这意味着如果我希望它以正确的方式格式化,我必须为每个单独的邮政编码复制此代码?
  • @JohanVergeer 这是解决问题的一种方法。否则,您可以使用 postal_code_format 函数本身中的新字符串对象更新 self.zip,正如我在更新的答案中所示。
【解决方案2】:

就个人而言,我建议您在 onchange_zip 函数中更改行:

self.postal_code_format(self.zip, self.country_id)

self.zip = self.postal_code_format(self.zip, self.country_id)

如果您采用这种方法,postal_code_format 函数只会返回一个格式化的邮政编码 - 它没有任何副作用(例如每次调用时更新 self.zip,这是一个副作用) - 无论调用它做什么它想要的格式化代码,在这种情况下 onchange_zip 更新 self.zip 值。现在如果 postal_code_format 被其他需要格式化邮政编码的代码调用,它不会影响 self.zip。

【讨论】:

    【解决方案3】:

    postal_code_format(self, zipcode, country):的行放

    self.zip = zipcode
    

    注意:无需将邮政编码和国家/地区作为变量显式传递给函数

    def postal_code_format(self):
        country = self.country_id
        zipcode = self.zip
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-06
      • 1970-01-01
      • 2019-09-17
      • 2013-06-05
      • 1970-01-01
      • 2020-06-29
      • 1970-01-01
      相关资源
      最近更新 更多