22.02.2024 Views

Daniel Voigt Godoy - Deep Learning with PyTorch Step-by-Step A Beginner’s Guide-leanpub

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Static Method

The “@” indicates that the method sitting below it, _visualize_tensors(), is

being decorated by the staticmethod decorator function.

"What is a decorator?"

Python decorators is a big topic on its own, too involved to explain here. If

you want to learn more about it, check Real Python’s "Primer on Python

Decorators." [93] But I will not leave you without a working knowledge of what

that particular (and somewhat common) decorator does.

The @staticmethod decorator allows the method to be called on an

uninstantiated class object. It is as if we’re attaching a method to a class but

that method does not depend on an instance of the class it is attached to.

It is easy to see why: In every other method we have created so far for the

StepByStep class, the first argument has ALWAYS been self. So, those

methods had access to the class they belonged to; better yet, they had access

to a particular instance and its attributes. Remember the Dog class? The

bark() method knew the name of the dog because its first argument was the

instance representing the dog (self).

A static method does not have a self argument. The inner

workings of the function must be independent of the

instance of the class it belongs to. The static method can

be executed from the class itself instead of from one of its

instances.

Let me illustrate it with yet another silly example:

class Cat(object):

def __init__(self, name):

self.name = name

@staticmethod

def meow():

print('Meow')

390 | Chapter 5: Convolutions

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!