2

I am trying to call the __init__ variable as a default variable but it is not calling

class test1:
    def __init__(self,name):
        self.name = name
    def method1(self,name2=self.name):
        return name2

If I call the function like

from test import test1
ma = test1("mkHun")

va = ma.method1() # Here I am expected output is mkhun

ca = ma.method1("new name")

In JavaScript this features is called as default parameters. Is this features is available in python or something problem with my code?

1
  • You cannot use self as a default parameter because it is not defined unlike javascript. or if you like, you can use None as a default parameter then check it in code, i know it would be good if the default parameter can use self but not. Commented Feb 23, 2018 at 5:21

2 Answers 2

4

Here's one way to achieve similar functionality. Others may have a more pythonic way. Code inspired by the docs here

class test1:
    def __init__(self, name):
        self.name = name

    def method1(self, newName=None): 
        if newName is not None:
            self.name = newName
        return self.name


ma = test1("mkHun")

va = ma.method1() # Here I am expected output is mkhun
print(va)

ca = ma.method1("new name")
print(ca)
Sign up to request clarification or add additional context in comments.

Comments

0
class test1:
    def __init__(self,name):
        self.name = name

    def method1(self, name2="This would work"):
        """You can already use self.name here without taking it from the method argument
        since self.name always exists, you don't need to put it in the method arguments"""
        return name2


ma = test1("mkHun")

va = ma.method1() # Here I am expected output is mkhun

ca = ma.method1("new name")

print(ma.name, "--->", va,"--->", ca)

self.variable is in reach for every method you define inside the class but @staticmethod, so you can simply give it a None as default argument and inside your method if the argument is None use the self.name and if it is not None and the argument indeed exist, use it instead. Hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.