Difference Between Python two Class definitions -


i'm new programming , want know difference between these 2 class definitions? 1 better , safer definition? 1 instance variables or 1 constructor method?

thanks

class myclass1:      def doadd (self,val1=0,val2=0):          sum1=val1+val2          print("myclass1")          print ("{0}+{1}={2}".format(val1,val2,sum1))  class myclass2:       def __init__(self,val1=0,val2=0):          self.val1=val1          self.val2=val2      def doadd(self):          sum2=self.val1+self.val2          print("myclass2")          print("{0}+{1}={2}".format(self.val1,self.val2,sum2))   obj1=myclass1()  obj1.doadd(1,2)  obj2=myclass2(1,2)  obj2.doadd() 

myclass1  1+2=3  myclass2  1+2=3 

myclass1

you may want addition , store sum in __init__() method avoid having recalculated every time doadd() called. , @gragas says, method lets store data later use in other methods.

myclass2

you're not using object oriented features here, might regular function.

def doadd(val1=0, val2=0):     return val1 + val2  print(doadd(1, 2)) 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -