0

I want to pass the value supplied to the class parameter to a function in the same class as it's default arguments, so that i could reuse the function to do another calculation with a different parameter value.

I'm working on creating an ip address calculator as a challenge for me to help learn python programming.

But Pycharm says "Unresolved reference 'self' "

Code:

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.
Kwame Benqazy
  • 45
  • 1
  • 6
  • 2
    Function default values are evaluated at the time the function was originally defined. The *class* didn't even exist yet, much less any instance of the class to have a meaningful `self` value. – jasonharper Aug 20 '20 at 16:07
  • 1
    Also: https://stackoverflow.com/questions/7371244/using-self-as-default-value-for-a-method and https://stackoverflow.com/questions/8131942/how-to-pass-a-default-argument-value-of-an-instance-member-to-a-method – Tomerikoo Aug 20 '20 at 16:12

1 Answers1

2

Use another default value and then check:

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

even shorter thanks to @CamiEQ:

def validate_subnetmask(self, input_subnetmask=None):
    input_subnetmask = input_subnetmask or self.subnet_mask
Banana
  • 2,295
  • 1
  • 8
  • 25