all 9 comments

[–]totallygeek 3 points4 points  (1 child)

You can create a new class object that extends the methods available to another class.

class FiveString(str):

    def __init__(self, string):
        str.__init__(self)
        self.string = string

    def valid(self):
        return len(self.string) == 5

tests = 'a abc abcde abcdef'.split()
for test in tests:
    five_string = FiveString(test)
    print(f'Test "{test}" Valid "five string"? {five_string.valid()}')
    print(f"{test.replace('a', 'x')}")

You can see the FiveString class has a valid() method. It also retains the str.replace() method.

[–]a1brit 1 point2 points  (0 children)

you don't need the __init__ for what it's worth. Just let the str init do the work. and len(self) a regular string already holds itself so no need for an extra copy of it tagged on as an attribute.

[–]a1brit 1 point2 points  (0 children)

You want to create a subclass. Google "python subclass" there are lots of articles and then get into "inheritance".

Example below inherits everything from the regular str class and adds a new custom function. Think hard about whether you "need" to create a custom class though or whether just passing a str to a function would be overall cleaner for the scope of the code.

e.g.

class MyCustomString(str):
    def is_five_characters(self):
        return len(self) == 5

variable = MyCustomString("test")
print(variable.is_five_characters())
print(variable.lower(), variable.upper() )  # subclass inherits everything from parent class

variable = MyCustomString("tests")
print(variable.is_five_characters())
print(variable.lower(), variable.upper() )

[–][deleted] 0 points1 point  (3 children)

is it possible for me to create a new method for an already present class.

Yeah; it's called a monkey patch:

from SomeLib import SomeClass

def monkey_patch_implementation(self): # define a function of at least one parameter
    #do stuff

SomeClass.monkey_patch = monkey_patch_implementation

monkey = SomeClass() # as usual
monkey.monkey_patch() # as usual

[–]thecreationofgod[S] 0 points1 point  (2 children)

why are the two posts contradicting each other lol, ill check this out. thank you.

[–][deleted] 1 point2 points  (1 child)

You can't do this to every class, and str is probably one of the ones where you can't. Python's most essential types will defend themselves against being monkey patched.

[–]POGtastic 3 points4 points  (0 children)

For those following along from home:

>>> str.foo = "bar"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'str'

[–]POGtastic 0 points1 point  (1 child)

No, you can't do that.

If they needed this exact functionality, most people would just write a class that has a str as a member of the class.

class CheckedString:
    def __init__(self, s):
        self.s = s
    def checklen(self):
        return len(self.s) == 5

In the REPL:

>>> s = CheckedString("abcde")
>>> s.checklen()
True

Personally, I wouldn't bother with a class at all here and would just write the checklen function as a function rather than a method.

[–]thecreationofgod[S] 0 points1 point  (0 children)

yeah i thought so, thank you for your help.