Home > Net >  Making Dot function python
Making Dot function python

Time:02-02

Is it possible to make a dot function that is var.function() that changes var? I realise that i can do:

class Myclass:
   def function(x):
      return 2
Myclass.function(1):

But i want to change it like the default python function.

def function(x):
   return(3)
x=1
x.function()
print(x)

and it returns

>>> 3

CodePudding user response:

class Myclass:
  def __init__(self, num):
    self.num = num
  
  def function(self):
    self.num  = 1

  def __str__(self):
    return str(self.num)

x = Myclass(3)
x.function()
print(x)

CodePudding user response:

This is weird usage. I suggest you to create custom class to do that, try using @property inside it if you don't want to call function in code.

  •  Tags:  
  • Related