Object Oriented
Method
Python
class Person:
def greet():
print("Hi!")
Methods are actions performed on objects.
Methods are like functions, They may get some input and may return a value.
If a method finishes without returning anything, the return value will be None
.
class Person:
# ...
def getName(self):
return self.name
def setName(self, name):
self.name = name
def sleep(self, fromTime, duration):
output = self.getName() + " slept from " + \
str(fromTime) + " for " + str(duration) + " hours."
print(output)
Parameters are inputs to methods.
Parameters are separated by comma (,
).
Parameters are passed by assignment (reference values).
person1 = Person()
person1.setName("Sam")
name = person1.getName() # Sam
person1.sleep(10, 7) # Sam slept from 10 for 7 hours.
Methods of an object can be accessed like any properties on it.
Notice although in method definitions the first parameter is self
, when a method is called we are not passing anything for that.
Arguments can also be passed to a method with key-value syntax (Keyword Arguments). You can learn more about this in Function Topic.