0
0
Pythonprogramming~5 mins

Self reference in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does self mean in a Python class?

self is a way for an object to refer to itself inside its methods. It lets the object access its own attributes and other methods.

Click to reveal answer
beginner
Why do we need to use self in method definitions?

Because Python does not automatically pass the object to methods. self is the first parameter that receives the object when a method is called.

Click to reveal answer
beginner
How do you use self to change an object's attribute inside a method?

You write self.attribute_name = new_value inside the method to update the object's attribute.

Click to reveal answer
intermediate
What happens if you forget to include self as the first parameter in a method?

Python will raise an error because it expects the method to receive the object as the first argument, but it won't get it.

Click to reveal answer
intermediate
Can self be named something else?

Yes, but self is the strong convention in Python. Using other names can confuse readers.

Click to reveal answer
In Python, what does self represent inside a class method?
AThe instance of the class calling the method
BA global variable
CA class method decorator
DA local variable inside the method
What will happen if you define a method without self as the first parameter and try to call it on an object?
AIt will work normally
BPython will raise a TypeError
CThe method will be treated as a static method
DThe method will ignore the object
Which of these is the correct way to set an attribute name inside a method using self?
Aself->name = 'Alice'
Bname = 'Alice'
Cself.name = 'Alice'
Dset self.name = 'Alice'
Is it mandatory to name the first parameter self in Python class methods?
AYes, it must be <code>self</code>
BYes, or the code will not run
CNo, you can omit it
DNo, but it is strongly recommended
What is the role of self when calling another method inside the same class?
AYou use <code>self.method_name()</code> to call it on the same object
BYou call methods directly by name without <code>self</code>
CIt is not needed to call other methods
DYou must import the method first
Explain what self means in Python classes and why it is important.
Think about how an object talks about itself inside its own methods.
You got /4 concepts.
    Describe how you would use self to change an attribute inside a class method.
    Imagine you want to update a property of your own object.
    You got /3 concepts.