1c. Instance Methods and Attributes Flashcards

1
Q

What does an “instance” method/attribute mean?

A

It means a class method or attribute whose value may differ from instance to instance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Can you only create instance attributes/methods inside the __init__ function?

A

No. You can do it elswhere, too.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you differentiate an attribute or a method that’s considered “internal” to a class and shouldn’t be accessed from the outside?

A

Internal methods/attribute names are prefixed with an underscore (_) by convention.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Can methods/attributes that have an underscore (_) suffix be accessed from outside the function?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you test whether an object has a certain attribute?

eg. object=book, attribute=_discount

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does an attribute or a method with a double underscore (__) do?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Is there a way to access a class attribute or method that has a double underscore (__) prefix?

A

Yes. Double underscore is not a perfect mechanism and there is a way around.

class=Book
object=book
attribute=__secret

solution=book._Book__secret

How well did you know this?
1
Not at all
2
3
4
5
Perfectly