问题
I am trying to create a class which takes a URL and allows me to split it into parts and return each of the scheme, server, and path.
class SimpleURL:
def __init__(self,url):
self.url=url
def scheme(self):
return url.split("://")[0]
def server(self):
return url.split("/")[2]
def path(self):
return url.split(url.split("/")[2])[1]
test_url = SimpleURL("https://gumgoose.com/larry/friendo")
Then, if I run
test_url.scheme()
or any server or path, I get the error
NameError: name 'url' is not defined
I am able to make it work if I assign the url to the variable "url" outside of the function, but to my understanding, the line beginning "test_url" should be doing that for me.
Can anybody shed some light onto this for me?
回答1:
Within all of your class methods, you will need to explicitly use self
to refer to all other class methods and attributes.
def scheme(self):
return self.url.split('://')[0]
If you do not do this, Python will only search the local scope within your method and the global scope. That is why if you define url
outside of your class, you don't have any issues.
回答2:
Python requires you reference the instance object too i.e. return self.url.split('://')[0]
来源:https://stackoverflow.com/questions/36103486/python-creating-a-class-x-object-has-no-attribute-split