2

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.

4
  • 1
    You mean you want to know if you can add a new method to the str() type. The answer is: no, not directly, you'd have to subclass. Commented Oct 16, 2014 at 15:48
  • What exactly is the problem or doesn't work here? Commented Oct 16, 2014 at 15:49
  • 2
    @MartijnPieters well he could use github.com/clarete/forbiddenfruit ... but just cause you can does not mean you should Commented Oct 16, 2014 at 15:50
  • @JoranBeasley: whohoo, didn't know about that project. Yup, still not something I'd actually use, but cool. Commented Oct 16, 2014 at 15:56

6 Answers 6

5

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")
Sign up to request clarification or add additional context in comments.

3 Comments

It's called "curse" for a reason!
should I make that disclaimer bolded? :P
@JoranBeasley You might want to take a look at the new DynamicClassAttribute in 3.4. That is really evil.
3

It feels like you want to monkey patch a method onto this. If so, then welcome to the dark side young one. Let us begin the cursed ritual. In essence you want to monkey patch. All we need is a little monkey blood. Just kidding. We need type.MethodType. But note, that you cannot monkey patch stdlib types:

>>> 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'

But that won't stop you from causing havoc in other classes:

>>> 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'

You see how easy that was? But we're just getting started. This is just a mere instance lets kill a class now shall we? The next part will get you laughing maniacally:

>>> 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'

After this, if you do not feel evil. Then you must come over to my evil lair, where I shall show you more evil tricks and share cookies.

Comments

2

Self has no special meaning - it is just a variable name. Its use in classes is merely conventional (so it may be confusing to use it elsewhere).

You can, however, set the properties of a class after-the-fact, and these could be class methods or instance methods (the latter with "self" by convention). This will NOT work with the built-in classes like str, though [edit: so you'd have to "curse" or subclass, see other answer]

Comments

2

In

def ispalendrome(self)

there's no need to name the parameter self (indeed, it's a bit misleading), as this isn't an instance method. I would call it s (for string):

def is_palindrome(s):

What you may be referring to is the use of bound methods on the class, where:

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

is equivalent to:

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

In this particular case, for example:

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

Comments

0

In Python the first argument to a class method is the object instance itself, by convention it is called self. You should prevent using self for other purposes.

To explain it more detailed:

If you have a class

class A(object):
    def __init__(self):
        self.b = 1

and you make an instance of it:

a = A()

this calls the init method and the parameter self if filled with a fresh object. Then self.b = 1 is called and add the attribute b to the new object. This object is then going to become knows as a.

Comments

0

"self" is the name of the first parameter to a function - like any parameter, it has no meaning outside of that function. What it corresponds to is the object on which that function is called.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.