0

I have a user defined function in the code below. Is there a way for me to re-write it with different syntax where I don't use brackets around the variable I want but rather have the function as a method such as .printfunction. Is there a way using classes and methods to rewrite the function as a method rather than a user-defined function?

The desired output needs to be xY .

def printfunction(var2):
    return "x" + var2

printfunction("Y")

def printfunction(var2):
    return "x" + var2

#Desired Syntax
var1 = "x"
var1.printfunction("Y")
martineau
  • 119,623
  • 25
  • 170
  • 301
AnalysisNerd
  • 111
  • 2
  • 16
  • You have to create a class and make that function a class method. – DYZ Dec 23 '18 at 21:52
  • How do I do that? I am relatively new to python and am really confused. Thanks – AnalysisNerd Dec 23 '18 at 21:54
  • "_I am relatively new to python_": Learn one bit at a time. Online courses, textbooks, tutorials. That's the only proper way. – DYZ Dec 23 '18 at 21:56
  • 2
    Not sure why anyone would downvote this question. Check here: https://stackoverflow.com/questions/4699179/add-custom-method-to-string-object for a better answer than I can give but in essence, you can't (in Python) override a string in the way you want. You can create a new class as @DYZ says and the link should help. – grayson Dec 23 '18 at 22:11
  • 2
    https://docs.python.org/3/tutorial/classes.html – Patrick Artner Dec 23 '18 at 22:12
  • Thank you so much @grayson . Really appreciate it!!! – AnalysisNerd Dec 23 '18 at 22:17
  • Thank you so much @Patrick Artner . Really appreciate it !!! – AnalysisNerd Dec 23 '18 at 22:17

2 Answers2

1

I'm not sure what version of python you are running on but this one works for me.

class String():
    def __init__(self,str):
        self.str = str
    def printfunction(self,append_this):
        print(self.str + append_this)


var1 = String('x')
var1.printfunction('Y')
Aven Desta
  • 2,114
  • 12
  • 27
0

Thanks to the advice from @grayson and @Patrick Artner. I am able to answer my question

class Strgcust(str):
     def printfunction(self, var1):
             return (self + var1)

var1 = Strgcust("x")

var1.printfunction(str("Y"))
AnalysisNerd
  • 111
  • 2
  • 16
  • 1
    Python has a built-in module named `string`, so it would be a good idea to name your class something else—`String` would avoid the problem and be in accordance with the advice in [PEP 8 - Naming Conventions](https://www.python.org/dev/peps/pep-0008/#naming-conventions) which says class names should have their first letter Capitalized. – martineau Dec 23 '18 at 22:37