darksideofthesun
darksideofthesun

Reputation: 621

How to override an attribute in a class' __init__ method?

If there's a class like:

class MyFunObject(object)
    def __init__(self):
        self.url = "http://myurl.com"

When I instantiate that class, can I not override the url attribute somehow?

If I do:

server = MyFunObject(url="http://www.google.com")

I get:

TypeError: __init__() got an unexpected keyword argument 'url'

Is there way to override an attribute that's defined in the class' __init__() method?

Upvotes: 1

Views: 1110

Answers (2)

Kyle
Kyle

Reputation: 1170

If you don't want to / can't change the code of the class, remember that a Python object's attributes are all public. So unless you're concerned with changing url before __init__() does any further processing, you can do the following:

>>> server = MyFunObject()
>>> server.url = 'http://www.google.com'
>>> print(server.url)
'http://www.google.com'

Upvotes: 0

user5777975
user5777975

Reputation:

You can try this:

class MyFunObject(object):

    def __init__(self, url="http://myurl.com"):
        self.url = url

    def Printurl(self)
        print(self.url)

obj = MyFunObject("http://www.google.com")
obj.Printurl()

Output:

http://www.google.com

If suppose:

 obj1 = MyFunObject()
 obj1.Printurl()

Output:

 http://myurl.com

Explanation:

As your function call is having a keyword argument url it is expecting the parameter in the __init__. If you add default value in __init__ if the user didn't pass the argument in object declaration then it will take the default one.

Upvotes: 2

Related Questions