Class methods

We saw in the previous section on Bound and unbound methods how methods are either bound to an instance of a class or remain in a state as unbound methods. Class methods are different. They are always bound methods. They are bound to the class itself.

We will first describe the syntactic details and then give some examples to show what these methods can be used for. To indicate that a method is a class method the decorator line precedes the method definition:

@classmethod

While standard methods make a reference to an instance by the use of their first argument, the first argument of a class method refers to the class itself. By convention the first argument is called self for standard methods and cls for class methods.

  • Standard case:
      class A:
          def func(self,*args):
               <...>
  • Class method case:
      class B:
          @classmethod
          def func(cls,*args):
               <...>

In practice, class methods may be useful for executing commands before an instance is created, for instance, in a preprocessing step. See the following example:

In this example we show how class methods can be used to prepare data before creating an instance:

class Polynomial:
    def __init__(self, coeff):
        self.coeff = array(coeff)
    @classmethod
    def by_points(cls, x, y):
        degree = x.shape[0] - 1
        coeff = polyfit(x, y, degree)
        return cls(coeff) 
    def __eq__(self, other):
        return allclose(self.coeff, other.coeff)

The class is designed so, that a polynomial object is created by specifying its coefficients. Alternatively, the by_points class method allows us to define a polynomial by interpolation points. We can transform the interpolation data to the polynomial coefficients even when no instance of Polynomial is available:

p1 = Polynomial.by_points(array([0., 1.]), array([0., 1.]))
p2 = Polynomial([1., 0.])

print(p1 == p2)  # prints True

Another example of a class method is presented in an example later in this chapter. In that example, a class method is used to access information related to several (or all) instances from this class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.199.184