I recently came across the following function: def generic_method(self, *args)
And I read that this means that one can access any class attributes by calling self.attribute_name
without having to pass it into the method signature.
The full function read
class PacketContext:
def __init__(self, capture_tstamp=None):
self.capture_tstamp = capture_tstamp
def generic_method(self, *args):
self.context = PacketContext()
While I understand the first part, what does it mean by
without having to pass it into the method signature?
CodePudding user response:
As stated in the comments, the *args
have nothing to do with the ability to access attributes with self.attribute_name
.
The signature of a function, so to speak is the definition of the interaface the function offers. In other words: "What do you need to pass and what do you get in return?" Example:
def foo(int i, bool b) -> bool:
return i > 5 or b
Here, the signature is "Give me an int i
and a bool b
and I'll return a bool
.
The self
argument is a little special. If you add the self
argument to a function in Python, it indicates that this is an instance method.
This means that the function requires a class to be instantiated before the method can be run on an the instance of an object.
Example:
class MyClass:
def __init__(self, instance_variable):
self.instance_variable = instance_variable
def my_method(self, *args):
print(self.instance_variable)
if __name__ == "__main__":
instance_of_my_class = MyClass(instance_variable="Great")
# Notice how my_method is called
instance_of_my_class.my_method()
# Internally, Python does the following when it encounters the line above
my_method(self=instance_of_my_class)
Now what they (to my understanding) mean by
without having to pass it into the method signature?
is that you didn't have to specify instance_variable
in the signature of my_method
. Because it is an instance method, you can access all attributes of the instance via self
.