Reputation: 16002
Lets say I have a class like this:
class SomeClass:
some_property = 'property'
def get_some_property(self):
return self.some_property
def some_method(self):
pass
What is difference (if any) between var1
and var2
in the following:
def some_method(self):
var1 = self.some_property
var2 = self.get_some_property()
For a less abstract example of this question, consider the FormMixin
class in django.generic.views.edit
, which looks something like this:
class FormMixin(ContextMixin):
"""Provide a way to show and handle a form in a request."""
initial = {}
form_class = None
success_url = None
prefix = None
...
def get_form_class(self):
"""Return the form class to use."""
return self.form_class
def get_form(self, form_class=None):
"""Return an instance of the form to be used in this view."""
if form_class is None:
form_class = self.get_form_class()
return form_class(**self.get_form_kwargs())
The method get_form_class
returns the form_class
property of self, but isn't this exactly the same as calling self.form_class
?
Upvotes: 1
Views: 101
Reputation: 780798
Using functions makes it easy to have different classes with the same interface, but different implementations. Some implementations may store the value in an attribute, while others have to compute it.
A classic demonstration of this is two classes for representing vectors, either using cartesian or polar coordinates. By accessing the coordinates using methods, you can interchange them.
import math
class cartesian_vector():
def __init__(self, x, y):
self.x = x
self.y = y
def getX(self):
return self.x
def getY(self):
return self.y
def getR(self):
return math.sqrt(self.x**2 + self.y**2)
def getTheta(self):
return math.atan(self.y/self.x)
class polar_vector():
def __init__(self, r, theta):
self.r = f
self.theta = theta
def getX(self):
return self.r * math.cos(self.theta)
def getY(self):
return self.r * math.sin(self.theta)
def getR(self):
return self.r
def getTheta(self):
return self.theta
Upvotes: 1