In Java, we can use an object’s
.getClass() method to find out what class it belongs to. In Python, we use the
type() function. So, for example, if we go back to our
Car example, you create a
my_car an instance of
Car?” And we get that it’s
True. But remember,
Car in the last version you looked at inherited from
Device, so I can also ask “Is
Device?” And we can get that that’s
True as well.
Java has class static methods:
getFields(), which gives you an array of all of its public fields, and
getDeclaredMethods(), which will return the public methods. To get similar information from a Python class, you would use the directory function, or
So I can say “Let’s print the value of
dir(),” call it on
my_car, and we get this collection of all of the attributes and fields—the ones we’ve defined, and the ones we’ve inherited that can be used for this
So I could say, for example, “Print the result of
getattr()” taking two parameters,
my_car followed by one of its attributes. So, for example, I can ask about
.voltage attribute, or I could ask about a method.
Lastly, we can actually use reflection to call methods.
getattr() doesn’t distinguish between methods and variables, so we can use another function called
callable(), which will tell us if the attribute we’ve provided is something that you can call—for example, a function or a method.
04:10 So from the directory listing of the object, we can now reduce that to those things that we can actually call. And we can actually use that to call a particular object’s method through this process of reflection.
Now, the collection generated from the directory listing is just a collection of strings, so a method name is just a string. The actual attribute, the actual method it refers to, we’re going to have to obtain through the
getattr() function call.
So at this point,
attr could be a field, it could be a method. We want to make sure it’s a method, so if it is callable—if the attribute is something callable—we want to see if it is the
And it calls our string function.
Car silver : fusion : 2018. And so there are just a few techniques of using the object to find out information and use information by itself, called reflection. Next, we’ll wrap everything up.
Become a Member to join the conversation.