Python - 创建Class-x对象没有属性“split” [英] Python-Creating a Class- x object has no attribute 'split'

查看:326
本文介绍了Python - 创建Class-x对象没有属性“split”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个类,它接受一个URL,并允许我把它分成部分,并返回每个方案,服务器和路径。

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()


$ b b

或任何服务器或路径,我得到错误

or any server or path, I get the error

   NameError: name 'url' is not defined

如果我将url指定给函数外的变量url,根据我的理解,开始test_url的行应该是为我做的。

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?

推荐答案

在所有类方法中,您需要明确使用 self 来引用所有其他类方法和属性。

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]



如果不这样做,Python只会在方法中搜索本地作用域。这就是为什么如果你在类外定义 url ,你没有任何问题。

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.

这篇关于Python - 创建Class-x对象没有属性“split”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆