Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using self in python, outside of a class

I am a bit unsure how to use self outside of a class. A lot of built in methods in python use self as a parameter and there is no need for you to declare the class; For example, you can use the string.upper() command to capitalize each letter without needing to tell python which class to use. In case I'm not explaining myself well, I have included what my code looks like below.

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

Note: I understand there are other ways of accomplishing this task, but I would like to know if this is possible. TYVM.

like image 999
PVNRT Avatar asked May 07 '26 20:05

PVNRT


1 Answers

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

note that just because you can does not mean its a good idea

alternatively it is much better to just do

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

ispalendrome("hello")
like image 192
Joran Beasley Avatar answered May 09 '26 10:05

Joran Beasley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!