【问题标题】:How to pass reference of a class parameter value to a function default argument value within the same class [duplicate]如何将类参数值的引用传递给同一类中的函数默认参数值[重复]
【发布时间】:2020-08-20 15:59:32
【问题描述】:

我想将提供给类参数的值传递给与默认参数相同的类中的函数,以便我可以重用该函数以使用不同的参数值进行另一次计算。

我正在努力创建一个 IP 地址计算器,以帮助我学习 Python 编程。

但是 Pycharm 说“未解析的引用'self'”

代码:

class IPOctet:

    def __init__(self, ip_address, subnet_mask):
        self.ip_address = ip_address
        self.subnet_mask = subnet_mask

    def validate_subnetmask(self, input_subnetmask = self.subnet_mask):
        # this function validates the input_subnetmask value to check if its a numeric value and 
        # returns the value when validated.

        # ...and i want the [input_subnetmask value] to be [self.subnet_mask] as its default arugument
        #  or any value passed into it when called.

【问题讨论】:

标签: python python-3.x


【解决方案1】:

使用另一个默认值,然后检查:

def validate_subnetmask(self, input_subnetmask=None):
    if input_subnetmask is None:
        input_subnetmask = self.subnet_mask

感谢@CamiEQ,更短:

def validate_subnetmask(self, input_subnetmask=None):
    input_subnetmask = input_subnetmask or self.subnet_mask

【讨论】:

  • 你可以让它更短:input_subnetmask = input_subnetmask or self.subnet_mask
  • 好的,这需要else语句吗?
  • @KwameBenqazy 不,只要在这个函数定义下写你的代码。
  • @CamiEQ 我认为明确的要好得多。我们不知道input_subnetmask 是什么类型,例如表示0.0.0.0 的有效掩码可能是虚假的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-28
  • 1970-01-01
  • 2012-05-22
  • 1970-01-01
相关资源
最近更新 更多