What type of methods are called from the class itself?
Recall that a method is an attribute of a class that is a function. For example, “append” is a method that is defined for the Show # create an instance of the `list` class/type # and invoke the instance method `append` >>> a = [1, 2, 3] >>> a.append(-1) >>> a [1, 2, 3, -1] # create an instance of the `str` class/type # and invoke the instance method `capitalize` >>> b = "moo" >>> b.capitalize() 'Moo' Here we will encounter three varieties of methods:
whose differences are relatively minor but are important to understand. The functions “append” and “capitalize” are both examples of instance methods, specifically, as they are designed to be invoked by a particular list instance and string instance, respectively. We have already worked with the instance method Instance MethodsAn instance method is defined whenever a function definition is specified within the body of a class. This may seem trivial but there is still a significant nuance that must be cleared up, which is that ‘ class Dummy: def func(x): """ An instance method that returns `x` unchanged. This is a bad version of this instance method!""" return x We can call this method from the class object but something strange happens when we try to call # calling `func` from an instance of `Dummy` produces # an unexpected error >>> inst = Dummy() >>> inst.func(2) TypeError: func() takes 1 positional argument but 2 were given At first glance, this error message doesn’t seem to make any sense. It is indeed true that Important! When you call an instance method (e.g. So according to this, # verifying that `inst` is being passed as the first argument # of the instance-method `func` # note the memory address of the Dummy-instance `inst` >>> inst <__main__.Dummy at 0x284f0008da0> # `inst.func()` automatically receives `inst` as the # input argument, which is then returned unchanged >>> inst.func() <__main__.Dummy at 0x284f0008da0> # `inst` is indeed being passed to, and # returned by, `func` >>> out = inst.func() >>> inst is out True Note that this “under the hood” behavior only occurs when the method is being called from an instance; this is why we didn’t face this issue when invoking >>> out = Dummy.func(inst) >>> out is inst True In its current form, there is no way for us to pass an argument to The self ArgumentWe will want to define our instance methods in a way that anticipates that Python will automatically
pass an instance object as the first argument. Thus if we want our method to accept \(N\) external argument, we should define its signature to have \(N+1\) arguments, with the understanding that Python will pass the instance object as the first argument. The accepted convention is to call this first argument # demonstrate the use of `self` in instance arguments class Number: def __init__(self, value): self.value = value def add(self, new_value): return self.value + new_value # calls __init__, setting self.value = 4.0 >>> x = Number(4.0) # `x` gets passed to `self` >>> x.add(2.0) 6.0 # Calling the instance method from the class object. # We must explicitly pass an object to `self` >>> Number.add(x, 2.0) 6.0 Note the utility of having Next, we will see that we can also define class-methods, which automatically have class objects get passed as their first arguments, and static methods, which do not have any objects passed to them under the hood. Reading Comprehension: Invoking Instance Methods Rewrite Class MethodsA class method is similar to an instance method, but it has a class object passed as its first argument. Recall that, when an instance method is called from an instance object, that instance object is automatically passed as the first argument to the method. By contrast, when a class method is called from a either a class
object or an instance object, the class object is automatically passed as the first argument to the method. Instead of calling this first argument To define a class method you must decorate the method definition with a special built-in decorator class Dummy: @classmethod def class_func(cls): """ A class method defined to simply return `cls` unchanged""" return cls # `Dummy` gets passed as `cls` automatically. # We defined `class_func` to return `cls` unchanged >>> Dummy.class_func() __main__.Dummy # `Dummy.class_func()` returns `Dummy` >>> out = Dummy.class_func() >>> out is Dummy True # `Dummy` gets passed as `cls` automatically # even when `class_func` is called from an instance >>> inst = Dummy() >>> inst.class_func() __main__.Dummy
>>> dict.fromkeys("abcd", 2.3) {'a': 2.3, 'b': 2.3, 'c': 2.3, 'd': 2.3} It is sensible that this is a class method rather than an instance method, as the method creates a brand new dictionary from scratch. It need only have access to the class dict: # assume all other dictionary methods are defined here @classmethod def fromkeys(cls, iterable, value=None): """ Creates a dictionary whose keys are the elements of `iterable`. All keys map to `value`. Parameters ---------- iterable: Iterable[Hashable] An iterable of valid dictionary keys (i.e. any object that is hashable). value : Optional[Any] The value that all of the keys will map to. Defaults to `None`. Returns ------- dict """ new_dict = cls() # equivalent to `dict()`: creates a new dictionary instance for key in iterable: new_dict[key] = value return new_dict Static MethodsA static method is simply a method whose arguments must all be passed explicitly by the user. That is, Python doesn’t pass
anything to a static method automatically. The built-in decorator class Dummy: @staticmethod def static_func(): """ A static method defined to always returns the string `'hi'`""" return 'hi' # A static method can be called from a class object # or an instance object; nothing gets passed to it # automatically. >>> Dummy.static_func() 'hi' >>> inst = Dummy() >>> inst.static_func() 'hi' Reading Comprehension SolutionsInvoking Instance Methods: Solution Rewrite
class Dummy: def func(self, x): return x Create an
instance of >>> inst = Dummy() >>> inst.func("hi") # `inst` is passed to the argument `self` 'hi' What will happen if you try to call
# Dummy.func("hi") would raise an error >>> Dummy.func(None, "hi") 'hi' Which type of method is called a class method?A class method is a method that can be invoked without reference to any object instance; these are called static methods in other languages. The term method usually refers to an instance method.
Can a class method be called from the class itself?A class method is a method that's shared among all objects. To call a class method, put the class as the first argument. Class methods can be can be called from instances and from the class itself. All of these use the same method.
What are methods of a class?Class methods are methods that are called on a class rather than an instance. They are typically used as part of an object meta-model. I.e, for each class, defined an instance of the class object in the meta-model is created. Meta-model protocols allow classes to be created and deleted.
Are static methods called class methods?The methods that belong to a class definition are called static methods. (Sometimes they are called class methods, but this is confusing.) A static method is part of a class definition, but is not part of the objects it creates. Important: A program can execute a static method without first creating an object!
|