0

Lets supose I have a function that makes add bigger spaces to my text.

def bigger_spaces(text):
    text = list(text)
    print(' '.join(text))

To execute it, i need to do bigger_spaces(my_text). how can I execute like this:

my_text.bigger_spaces()

I know I can make a class but then I have to add the string to that class first

6
  • I'd probably subclass str and then make text an instance of that class, rather than modifying the built-in str class. Commented Aug 4, 2019 at 17:21
  • 1
    Note that while it's considered a reasonable practice (in some quarters, not by any means all) to extend classes that shipped with the standard library in Ruby, that is not at all considered a responsible thing to do in Python... arguably more on account of cultural issues than actual runtime differences (there's a lot more appreciation for readability, predictability, maintainability, etc in the Python world). Commented Aug 4, 2019 at 17:23
  • create a class that has a function "bigger_spaces()" and a text as one property of that class then create object "my_text" as an instance of that class. Commented Aug 4, 2019 at 17:24
  • 1
    @rafa_rrayes, just because the other instance got an answer you don't like doesn't mean it wasn't the same question being asked. The answer is "no, you can't" -- intentionally so; in the Python world, we consider this kind of practice to be dangerous, inasfar as monkeypatching makes it harder to understand what code does on a read (increasing the amount of context that needs to be read and understood), even when it's putatively interacting only with built-in types. Commented Aug 4, 2019 at 17:31
  • 1
    Also Python isn't designed to support adding methods to built-in classes, and trying to brute-force it is a recipe for weird segfaults and memory corruption. Commented Aug 4, 2019 at 17:34

1 Answer 1

1
class MyString:
    def __init__(self, string):
        self.string = string
    def bigger_string(self):
        print(' '.join(self.string))

mystring = MyString("this is the string")
mystring.bigger_string()

output

t h i s   i s   t h e   s t r i n g

Dataclass in Python 3.7

from dataclasses import dataclass

@dataclass
class St:

    text : str

    def bigger(self) -> None:
        self.text = list(self.text)
        print(" ".join(self.text))

mys = St("Hello")
mys.bigger()

output

H e l l o
Sign up to request clarification or add additional context in comments.

1 Comment

Consider adding this answer on the canonical instance of the question, rather than here; that way, it's going to get a wider audience, and we avoid having folks' attention spread across multiple instances of the question where it could be focused on just one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.