Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Using Classes Methods and Attributes

00:00 Using Classes, Methods, and Attributes Sometimes you have one or more functions that operate on or with some global variables. In those cases, you can think of writing a class that turns the functions into methods and the global variables into instance attributes.

00:17 Let’s say you are coding an app to manage your bank account. You start by creating functions that operate on the account’s balance. In this code, you rely on a global variable to store the balance of your bank account.

00:34 You have three functions that provide common operations on the account balance. You can deposit money, you can withdraw money,

00:53 and you can check the current balance of your account. The main function defines a while loop that presents you with a text-based user interface.

01:04 And through this, you can tell the app to perform the desired operations on your account.

01:50 On screen, you can see the app in action. It works as expected. It allows you to make deposits, withdraw funds, and check your current balance.

02:18 Now, let’s say you don’t like depending on global variables too much and you decide to refactor the app using a class. To do this, you’ll need to take these steps: Define a class with an appropriate name.

02:31 In this example, Account is appropriate. Move the global variables into the class, converting them into instance attributes, and move the functions into the class as instance methods.

02:45 On screen, you can see the refactor code being written for the bank account management application. In this new version of the accounting program, you define a class called Account.

02:56 The class has an instance attribute to store the account’s balance. This attribute used to be the old balance global variable. You convert the deposit and withdrawal functions into instance methods with the current instance .self as the first argument.

03:18 Finally, inside the loop, you instantiate the Account class and call its methods on that instance to make the app work in the same way as the previous version.

03:51 Note that in this implementation, you don’t have a get_balance() method. To access the account balance, you can directly use the .balance attribute.

04:12 On screen, you can see the new class-based version in action and see that the functionality is identical.

04:36 In the next section of the course, you’ll take a look back at what you’ve learned.

Become a Member to join the conversation.