i have a class that will make multiple instances. whats the difference between making a method and calling that method versus making a class and a function then using that function on the class? Does the first cost more memory because the method is “instantiated”?
Example:
class myclass:
def __init__(self):
self.a=0
def mymethod:
print self.a
inst1=myclass()
myclass.mymethod
versus:
class myclass:
def __init__(self):
self.a=0
def myfunction(instance):
print instance.a
inst1=myclass()
myfunction(inst1)
Methods are really just functions that always receive a class instance as a first parameter (and happen to be declared within the scope of a class). The code of a method is shared across all instances, so you won’t be “instantiating” a method every time you make a class instance.
So, they are really equivalent; you use whatever is the clearest expression of your intent (readability counts!). If you are writing a function that always takes an instance of a specific class as an argument, it is probably clearest expressed as a method. If the function can operate on many different kinds of classes, it may be clearest as a function.