1c. Instance Methods and Attributes Flashcards
What does an “instance” method/attribute mean?
It means a class method or attribute whose value may differ from instance to instance.
Can you only create instance attributes/methods inside the __init__ function?
No. You can do it elswhere, too.
How do you differentiate an attribute or a method that’s considered “internal” to a class and shouldn’t be accessed from the outside?
Internal methods/attribute names are prefixed with an underscore (_) by convention.
Can methods/attributes that have an underscore (_) suffix be accessed from outside the function?
Yes. Underscore is only a convention that serves to tell developers that the attribute or the method is internal to the class. However, it doesn’t enforce this any further.
How do you test whether an object has a certain attribute?
eg. object=book, attribute=_discount
By using the hasattr
function like so:
hasattr(book, ‘_discount’)
This function will return True if the object has the given attribute, and False if not.
What does an attribute or a method with a double underscore (__) do?
It gets the Python interpreter to change the value of the attribute, so that other classes will get an error if they try to access it.
Is there a way to access a class attribute or method that has a double underscore (__) prefix?
Yes. Double underscore is not a perfect mechanism and there is a way around.
class=Book
object=book
attribute=__secret
solution=book._Book__secret