在类外使用Python中的self

2 投票
6 回答
14131 浏览
提问于 2025-04-27 23:27

我有点不太明白如何在类外使用self。在Python中,很多内置的方法都把self当作参数,但你不需要声明类。例如,你可以使用string.upper()这个命令来把每个字母变成大写,而不需要告诉Python使用哪个类。如果我解释得不太清楚,下面是我的代码示例。

def ispalendrome(self): return self == self[::-1]

largestProd = 999**2
largest5Palendromes = []
while len(largest5Palendromes) <= 5:
    if str(largestProd).ispalendrome(): largest5Palendromes.append(largestProd)
    largestProd -= 1
print largest5Palendromes

注意:我知道还有其他方法可以完成这个任务,但我想知道这样做是否可行。非常感谢。

暂无标签

6 个回答

0

"self" 是一个函数的第一个参数的名字 - 就像其他参数一样,它在函数外面没有任何意义。它所对应的是调用这个函数的对象。

2

在这里,“self”并没有特别的意思,它只是一个变量名。在类里面使用它只是个约定,所以在其他地方用可能会让人困惑。

不过,你可以在之后给一个类的属性设置值,这些属性可以是类的方法或者实例的方法(后者通常会用“self”)。不过,这种做法在像 str 这样的内置类中是行不通的【编辑:所以你得“咒骂”或者创建子类,看看其他的回答】。

2

def ispalendrome(self)

中,其实不需要把参数命名为self(实际上,这样命名有点误导),因为这不是一个实例方法。我会把它叫做s(代表字符串):

def is_palindrome(s):

你可能提到的是在类上使用绑定方法的情况,其中:

an_instance = TheClass()
an_instance.instance_method() # self is passed implicitly

等同于:

an_instance = TheClass()
TheClass.instance_method(an_instance) # self is passed explicitly

在这个特定的例子中,比如:

>>> "foo".upper()
'FOO'
>>> str.upper("foo")
'FOO'
3

感觉你想在这个方法上做一些修改。如果是这样的话,欢迎你来到黑暗的一面,小朋友。让我们开始这个诅咒的仪式吧。简单来说,你就是想修改一下方法。我们只需要一点“猴子血”。开个玩笑,其实我们需要的是 type.MethodType。不过要注意,你不能修改标准库里的类型:

>>> from types import MethodType
>>> def palindrome(self): return self == self[::-1]
...
>>> str.palindrome = MethodType(palindrome, str)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'str'

但这并不妨碍你在其他类里搞点小动作:

>>> class String(object):
...     def __init__(self, done):
...         self.done = done
...
...
...
>>> s = String("stanley yelnats")
>>> def palindrome(self): return self.done[::-1]
>>> s.palindrome = MethodType(palindrome, s)
>>> s.palindrome()
'stanley yelnats'

你看,这么简单吧?但这只是个开始。我们现在要对一个 class 下手,准备好笑得疯狂了吗?接下来的内容会让你笑得停不下来:

>>> from types import DynamicClassAttribute
>>> class String(object):
...     def __init__(self, done):
...         self.done = done
...
...
...
>>> s = String("cheese")
>>> def palindrome(self): return self.done[::-1];
...
>>> String.palindrome = DynamicClassAttribute(palindrome)
>>> s.palindrome
'eseehc'

如果看完这些你还不觉得自己有点邪恶,那就来我的邪恶基地吧,我会教你更多邪恶的把戏,还会分享一些 饼干

5

使用 https://github.com/clarete/forbiddenfruit

from forbiddenfruit import curse
def ispalendrome(self): #note that self is really just a variable name ... it doent have to be named self
    return self == self[::-1]
curse(str, "ispalendrome",ispalendrome)

"hello".ispalendrome()

请注意,虽然你可以这样做,但并不意味着这是个好主意

另外,直接这样做会更好

def ispalendrome(a_string):
    return a_string == a_string[::-1]

ispalendrome("hello")

撰写回答