-1

So I want to make a function like .isalpha() or .isnumerc(). Basically, a function where the input is before the command name. Here’s an example:

def string.text():
  print(string)

But that doesn’t work. It just says “Invalid Syntax”

I was expecting it to work like .lower() or .isnumeric() or .isalpha() or all those functions that have the input behind the function name.

Ajeet Verma
  • 2,938
  • 3
  • 13
  • 24
Snakey
  • 3
  • 3
  • 1
    take a look at this question https://stackoverflow.com/questions/352537/extending-builtin-classes-in-python you need to create a subclass of string and add there your own methods. – Sembei Norimaki May 23 '23 at 09:27
  • 1
    These are called "class/instance methods`. You create a class (possibly subclassing some other class) and then implement a method for this class. – matszwecja May 23 '23 at 09:29

2 Answers2

2

You are looking for sub classes in python

You have a base class such as str and a class that inherits from it eg: CustomStr

class CustomStr(str):
    def text(self):
       return "text"

Now simply create an instance of this class and you invoke your custom function on it

s = CustomStr("Hello world")
s.text()
>>text
InsertCheesyLine
  • 1,112
  • 2
  • 11
  • 19
0

What you are talking about is creating a method in an Object Oriented Programming language (which python can be)

here is a good explanation: https://www.techtarget.com/whatis/definition/method#:~:text=In%20object%2Doriented%20programming%20(OOP,the%20object%20that%20calls%20it.

but the gist is that you can create methods (just like functions but specific to a particular class) and then the way to call those methods is exactly how you described:

class.method()

Don't forget to put self as the first argument for the method.

I hope this helps