How to do it...

  1. Class methods can be decorated as well. Instance methods are the most common form of methods, that is, functions in classes. Here is cat_class.py with a few methods to work with:
        class Cat():
def __init__(self, breed, age):
"""Initialization method to auto-populate an instance"""

self.breed = breed
self.age = age

def cat_age(self):
"""Get the cat's age"""

return self.age

def breed(self):
"""Get the type of cat, e.g. short hair, long hair, etc."""

return self.breed

def __repr__(self):
"""Return string representation of Cat object.

Without this method, only the object's
memory address will be printed.
"""
return "{breed}, {age}".format(breed = self.breed, age = self.age)
  1. To utilize this class, create an instance of Cat, providing the initial parameters:
         chip = Cat("domestic shorthair", 4)
  1. Next, call the methods to ensure that they work:
  1. Notice that the methods are tied to a particular instance; they cannot be called on the generic Cat class:
  1. Static methods are methods that apply to all instances. They are denoted by the @staticmethod decorator prior to a method definition. Also, the method itself does not require a self argument in the definition (static_method.py):
        @staticmethod # This is required
def cry():
"""Static method, available to all instances and the class

Notice that 'self' is not a required argument
"""

return "Nyao nyao" # It's a Japanese cat
  1. Static methods can be applied to both instances and the class itself:

Notice that on lines 29 and 31, calling the static method without parentheses returns the memory location of the method; the method is not bound to an instance, but is available to the class as well. Only when parentheses are used (lines 30 and 32) will the correct return object be displayed.

  1. Class methods are identified by the @classmethod decorator prior to creating the method. In addition, the method argument is cls instead of self. The following code can be added after the static method in the previous example (class_method.py):
        @classmethod # This is required
def type(cls):
"""
Class method, available only to classes.

Notice that 'cls' is the argument, as opposed to 'self'
"""

if cls.__name__ == "Cat":
return "Some sort of domestic cat."
else:
return cls.__name__
  1. Now, when instance is made, the class it comes from is checked. If the generic Cat class is the generator, a message will be printed. If a subclass of Cat is used, then the name of the class is printed:
..................Content has been hidden....................

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