Module (61%)
Section (78%)

An example of using the static method

Imagine a class that represents a bank account, that is, a class that provides methods to operate on bank accounts. This may include a method that validates the correctness of the account number recorded in accordance with the IBAN standard.

This is a great place to introduce a static method, which, provided by the bank account class, will be used to validate the character string and will answer the question: can a given character string be an account number before the object is created?

To shorten the size of the sample code, the static method responsible for validation checks only the length of the string, and only those numbers whose length is 20 characters are treated as valid.

Note that for the purpose of validating three different character strings, it isn’t necessary to create class objects.

The result of the code presented:

We can use 88888888888888888888 to create a bank account The account number 7777 is invalid The account number 2222 is invalid

output


Code

class Bank_Account:
def __init__(self, iban):
print('__init__ called')
self.iban = iban

@staticmethod
def validate(iban):
if len(iban) == 20:
return True
else:
return False


account_numbers = ['8' * 20, '7' * 4, '2222']

for element in account_numbers:
if Bank_Account.validate(element):
print('We can use', element, ' to create a bank account')
else:
print('The account number', element, 'is invalid')
{{ dockerServerErrorMsg }} ×
{{ errorMsg }} ×
{{ successMsg }} ×