Methods work the same way as functions, where you can pass arguments into the method to be used. When these arguments are passed in, they do not need to be referenced with the self parameter, as they are not attributes, but rather temporary variables that the method can use:
# writing methods that accept parameters class Dog( ): def showAge(self, age):
print(age) # does not need self, age is referencing the parameter not an attribute
sam = Dog( ) sam.showAge( 6 ) # passing the integer 6 as an argument to the showAge method
Go ahead and run the cell. We’ll get an output of 6. After defining an instance of Dog, we called the method showAge and passed the argument of the integer 6 into the method. The method was then able to print out age. We did not need to say “self.age” because self is in reference to class attributes, not parameters.
Using Setters and Getters
In programming there is a concept called setters and getters. They are methods that you create to re-declare attribute values and return attribute values. We’ve seen how we can alter attribute values by directly accessing them; however, this can sometimes lead to problems or accidentally altering the value. Good practice is to create a method that will alter the attribute value for you and call that method when you need to set a new value. The same goes for when you want to access a given attributes value; instead of accessing it directly, you call a method that will return the value. This gives us a safer way to access an instances attributes. Let’s see how we can:
1| # using methods to set or return attribute values, proper programming practice 3| class Dog( ):
4| name = ' ' # would normally use init method to declare, this is for testing purposes
6| def setName(self, new_name):
7| self.name = new_name # declares the new value for the name attribute
9| def getName(self):
10| return self.name # returns the value of the name attribute
11| sam = Dog( )
13| sam.setName("Sammi")
15| print( sam.getName( ) ) # prints the returned value of self.name
Go ahead and run the cell. We’ve created two methods, one setter and one getter. These methods will generally have their respective keywords “set” and “get” at the beginning of the method names. On line 4 we define a setter to take in a parameter of new_name and change the attribute name to the value passed in. This is better practice to alter attribute values. On the 6th line we create a getter method that simply returns the value of the name attribute. This is better practice to retrieve an attributes value. Lines 9 and 10 call both methods in order to alter and print out the returned value.
Do'stlaringiz bilan baham: |