简体   繁体   中英

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?

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.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM