Home > OS >  How to access constructor parameter to use as default parameter of another method in Python?
How to access constructor parameter to use as default parameter of another method in Python?

Time:07-15

class Customer:
    def __init__(self , name, gender, address):
        self.name = name 
        self.gender = gender 
        self.address = address 
    
    def edit_profile(self, new_city, new_gender, new_address, new_name = self.name):
        self.name = new_name 

I am trying to set self.name from the constructor as default parameter for my method but getting error "self" is not defined. Why is it showing the error why can't I access self.name in defult parameter but I can access it inside the method with self.name

CodePudding user response:

You need to use a sentinel value like None, then check inside the body. self is not a keyword; it's just a parameter name that references an argument passed to the method. There is no instance available to get a name from when you define edit_profile.

def edit_profile(self, new_city, new_gender, new_address, new_name=None):
    if new_name is None:
        new_name = self.name
    ...
  • Related