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.

Methods, _methods, and __methods

Some programming languages, like Java, have three kinds of methods: public,

protected, and private. Public methods are the kind you’re most familiar

with: They can be called by the user.

Protected methods, on the other hand, shouldn’t be called by the user—they

are supposed to be called either internally or by the child class (the child

class can call a protected method from its parent class).

Finally, private methods are supposed to be called exclusively internally.

They should be invisible even to a child class.

These rules are strictly enforced in Java, but Python takes a more relaxed

approach: All methods are public, meaning you can call whatever method

you want. But you can suggest the appropriate usage by prefixing the

method name with a single underscore (for protected methods) or a double

underscore (for private methods). This way, the user is aware of the

programmer’s intention.

In our example, both _make_train_step_fn() and _make_val_step_fn() are

defined as protected methods. I expect users not to call them directly, but if

someone decides to define a class that inherits from StepByStep, they should feel

entitled to do so.

In order to make the additions to our code visually simpler; that is, without having

to replicate the full class every time I introduce a new method, I am resorting to

something that shouldn’t be used in regular circumstances: setattr. [65]

# ATTENTION! Using SETATTR for educational purposes only :-)

setattr(StepByStep, '_make_train_step_fn', _make_train_step_fn)

setattr(StepByStep, '_make_val_step_fn', _make_val_step_fn)

Using setattr is a hack, I can’t stress this enough! Please don’t

use setattr in your regular code.

184 | Chapter 2.1: Going Classy

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

Saved successfully!

Ooh no, something went wrong!