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

peiying410632
from peiying410632 More from this publisher
22.02.2024 Views

setattrThe setattr function sets the value of the specified attribute of a givenobject. But methods are also attributes, so we can use this function to"attach" a method to an existing class and to all its existing instances in onego!Yes, this is a hack! No, you should not use it in your regular code! Usingsetattr to build a class by appending methods to it incrementally serveseducational purposes only.To illustrate how it works and why it may be dangerous, I will show you alittle example. Let’s create a simple Dog class, which takes only the dog’sname as argument:class Dog(object):def __init__(self, name):self.name = nameNext, let’s instantiate our class; that is, we are creating a dog. Let’s call it Rex.Its name is going to be stored in the name attribute:rex = Dog('Rex')print(rex.name)OutputRexThen, let’s create a bark() function that takes an instance of Dog asargument:def bark(dog):print('{} barks: "Woof!"'.format(dog.name))Sure enough, we can call this function to make Rex bark:Going Classy | 185

bark(rex)OutputRex barks: "Woof!"But that’s not what we want. We want our dogs to be able to bark out of thebox! So we will use setattr to give dogs the ability to bark. There is onething we need to change, though, and that’s the function’s argument. Sincewe want the bark function to be a method of the Dog class itself, theargument needs to be the method’s own instance: self.def bark(self):print('{} barks: "Woof!"'.format(self.name))setattr(Dog, 'bark', bark)Does it work? Let’s create a new dog:fido = Dog('Fido')fido.bark()OutputFido barks: "Woof!"Of course it works! Not only new dogs can bark now, but all dogs can bark:rex.bark()OutputRex barks: "Woof!"186 | Chapter 2.1: Going Classy

bark(rex)

Output

Rex barks: "Woof!"

But that’s not what we want. We want our dogs to be able to bark out of the

box! So we will use setattr to give dogs the ability to bark. There is one

thing we need to change, though, and that’s the function’s argument. Since

we want the bark function to be a method of the Dog class itself, the

argument needs to be the method’s own instance: self.

def bark(self):

print('{} barks: "Woof!"'.format(self.name))

setattr(Dog, 'bark', bark)

Does it work? Let’s create a new dog:

fido = Dog('Fido')

fido.bark()

Output

Fido barks: "Woof!"

Of course it works! Not only new dogs can bark now, but all dogs can bark:

rex.bark()

Output

Rex barks: "Woof!"

186 | Chapter 2.1: Going Classy

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

Saved successfully!

Ooh no, something went wrong!