Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
    ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading