PVNRT
PVNRT

Reputation: 335

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.

Upvotes: 2

Views: 16473

Answers (6)

Nafiul Islam
Nafiul Islam

Reputation: 82440

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.

Upvotes: 3

Jon Kiparsky
Jon Kiparsky

Reputation: 7743

"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.

Upvotes: 0

Klaus D.
Klaus D.

Reputation: 14369

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.

Upvotes: 0

jonrsharpe
jonrsharpe

Reputation: 121964

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'

Upvotes: 2

mdurant
mdurant

Reputation: 28673

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]

Upvotes: 2

Joran Beasley
Joran Beasley

Reputation: 113930

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

Upvotes: 5

Related Questions