391,961 views
1 vote
1 vote
What is the scope of the variable hardness?

class pencil:
color = 'yellow'
hardness = 2
class pencilCase:
def __init__(self, color, art):
self.color = 'black'
self.art = 'wolf'
def __str__(self):
return self.color + " " + self.art
# main part of the program
pencilA = pencil()

limited to the pencilCase class

accessible to all parts of the program

limited to the pencil class

limited to the main part of the program

User Nikola Irinchev
by
2.9k points

2 Answers

24 votes
24 votes

Final answer:

The variable 'hardness' is limited to the pencil class and is accessible to all instances of this class but not outside of it. It is a class variable shared across all instances of the pencil class.

Step-by-step explanation:

The scope of the variable hardness is limited to the pencil class. It is a class variable that has been set within the pencil class, meaning it is accessible to all instances of the pencil class, but not outside of it. Variables defined in this way are class-level attributes, which means that they are not specific to any instance of the class but are shared across all instances. Therefore, the variable hardness is not restricted to just the pencilCase class or the main part of the program; it is specific to the pencil class and any instance of that class, such as pencilA.

User Cina
by
2.8k points
7 votes
7 votes

Answer:The variable petName is local to the class; This isdue to the fact that the variable was created in a function whose name begins with two underscores.

The variable color; This is created in the petCarrier class and is accessible to the entire function. This was not created in a function whose name begins with an underscore.

Step-by-step explanation:

User Mrc
by
2.4k points