0
0
Pythonprogramming~5 mins

Public attributes in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What are public attributes in Python classes?
Public attributes are variables defined inside a class that can be accessed and modified from outside the class freely.
Click to reveal answer
beginner
How do you define a public attribute in a Python class?
You define a public attribute by simply assigning a variable inside the class without any special prefix, for example: <code>self.name = 'Alice'</code>.
Click to reveal answer
beginner
Can you access public attributes from outside the class? Show an example.
Yes, you can access public attributes directly. Example:<br><code>class Person:<br>    def __init__(self, name):<br>        self.name = name<br>p = Person('Bob')<br>print(p.name)  # Outputs: Bob</code>
Click to reveal answer
beginner
What happens if you modify a public attribute from outside the class?
Modifying a public attribute from outside the class changes its value for that object. For example:<br><code>p.name = 'Charlie'</code> changes the name attribute to 'Charlie'.
Click to reveal answer
beginner
Are public attributes safe from accidental changes?
No, public attributes can be changed accidentally or intentionally from outside the class because they have no access restrictions.
Click to reveal answer
How do you access a public attribute named 'age' of an object 'person'?
Aperson->age
Bperson.age
Cperson.__age
Dperson._age
Which of these is a public attribute in Python?
Aself.__name
Bself._name
Cself.name
Dself.__name__
What happens if you try to change a public attribute from outside the class?
ANothing happens.
BPython raises an error.
CThe attribute becomes private.
DThe attribute value changes.
Which of these is true about public attributes?
AThey can be accessed and modified from outside the class.
BThey cannot be accessed from outside the class.
CThey are hidden by default.
DThey require special methods to access.
How do you define a public attribute inside a class constructor?
Aself.attribute = value
B_attribute = value
C__attribute = value
Dattribute = value
Explain what public attributes are and how you use them in Python classes.
Think about variables inside a class that anyone can see and change.
You got /4 concepts.
    Describe the difference between public attributes and private attributes in Python.
    Consider how naming affects access.
    You got /4 concepts.