Use dot notation to call a function without using parentheses

MRAB python at mrabarnett.plus.com
Tue Dec 22 07:20:01 EST 2020


On 2020-12-22 11:16, Walk More wrote:
> I am trying to use dot notation to call a function without using parentheses, see code section with ***
> I have looked into SimpleNamespace, namedTuple, dataclass... but no luck.
> Below is my sample code to date.
> Any suggestions?
> 
> 
> 
> class MyTest:
>      def __init__(self):
>          self.page1 = Page()
>          self.page1.top = Counts()
>          #self.page1.middle = Layout()
>          #self.page1.bottom = Layout()
>          
>          # access of variables created on the fly using dot notation work.
>          self.page1.top.item1 = 5
>          self.page1.top.name1 = "Harry"
>          print ("Variables created on the fly: ", self.page1.top.item1, self.page1.top.name1)
>          
>          
>          # access of a predefined class variable using dot notation work.
>          print ("Start of predefined class variable access: ", self.page1.top.totalCount)
>          self.page1.top.totalCount = 22
>          self.page1.top.totalCount = self.page1.top.totalCount + 3
>          print ("End of predefined class variable access: ", self.page1.top.totalCount)
>          
>          
>          # function calls using parentheses using dot notation work.
>          print ("Start of function calls: ", self.page1.top.getRunningSum())
>          self.page1.top.addRunningSum(5)
>          self.page1.top.addRunningSum(200)
>          endValue = self.page1.top.getRunningSum()
>          print ("End of function calls: ", endValue)
> 
> 
>          # *** This is the syntax I would like to use. ***
>          # function calls not using parentheses DO NOT WORK using dot notation.
>          self.page1.top.addRunningSum = 6
>          t = self.page1.top.getRunningSum
>          print (t)
>      
>      
> class Page ():
>      def __init__ (self):
>          pass
>      
>      
> class Counts():
>      def __init__ (self):
>          self.totalCount = 0
>      
>      def addRunningSum(self, indata):
>          self.totalCount = self.totalCount + indata
>      
>      def getRunningSum (self):
>          return self.totalCount
>      
> 
> if __name__ == "__main__":
>      MyTest()
> 
> #end of program
> 
It would be simpler just to access the totalCount attribute directly, 
but, in answer to your question, you can make it a property:

      @property
      def getRunningSum(self):
          return self.totalCount

and you'll then need to remove the parenthese where you're calling it.


More information about the Python-list mailing list