Within the definition of an instance method of some class with the following hea
ID: 3909694 • Letter: W
Question
Within the definition of an instance method of some class with the following header def some_method(self, obj_of_some_class): # details unimportant a programmer might utilize the special syntax self.some member to reasonably assist with which of the O To get at static/class data of the class being defined if there is a static/class attribute that has the name some_member but no instance attribute by that name in the calling object. To enhance readability, as an alternative to just using the attribute name by itself, since the calling object's instance data is assumed when we use the name of an attribute with, or without, the self. prepended. To get at instance data of the calling object, since without self. before the attribute name, some_member would be a local variable, not an attribute name. To get at data of a non-self object parameter that is passed to the method, in this case, data of the object referenced by the second parameter, obj_of_some_class. K2Explanation / Answer
class A:
"""
Sample class A
"""
def __init__(self):
"""
Constructor for class A
"""
self.some_member = 100
class B:
"""
Sample class B
"""
def __init__(self):
"""
Constructor for class B
"""
self.some_member = 200
def some_method(self, object_of_some_class):
"""
Parameters
----------
object_of_some_class : Object
"""
# Since below variable has same name as instance variable 'some_member' but we are not using self. before it,
# it will be treated as a local variable instead of instance variable
some_member = 300
print("Calling object's value: {}".format(self.some_member)) # prints the calling object's value
print("Some class object's value: {}".format(object_of_some_class.some_member)) # prints the some class object's value
print("Local variable's value: {}".format(some_member)) # prints the local variable's value
a_class_object = A() # creating A class' object
b_class_object = B() # creating B class' object
b_class_object.some_method(a_class_object) # calling object is B class type and passing A class type object to some_method
OUTPUT
--------------
Calling object's value: 200
Some class object's value: 100
Local variable's value: 300
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.