0

I am quite new to OOP in Python and I love the way it works. So I am experimenting a lot with it. I am trying to build a Freelancer class that allow users to register on a platform with a username but checks that the username does not exist in the database.

Here is my working approach:

class Freelancer:
    """Leaving this blank for now while I explore the functionality """
    number_of_sales = 0
    available_niches = ["Graphic design", "Art", "Data Analysis", "Music", "Business", "Writing and Translations"]
    usernames = []

    def __init__(self, username):
        self.username = _check_username(username)

    def _check_username(self, username):
        if self.username in Freelancer.usernames:
            print("This username already exist on our database, consider choosing another one")
        else:
            self.username = username
            Freelancer.usernames.append(self.username)
            print("You have successfully setup a username on our platform")

Testing this class and method here:

David = Freelancer("dave23")

Gives me the following error:

NameError: name '_check_username' is not defined

I would like a way to apply private methods in my class initialization. Is this possible?

JA-pythonista
  • 1,051
  • 11
  • 33
  • 4
    Need: `self.username = self.__check_username(username)` to i.e. needs 'self.' [call methods within class](https://stackoverflow.com/questions/5615648/python-call-function-within-class). Need `__` (i.e. double dash) to make method private [Private Methods](https://www.geeksforgeeks.org/private-methods-in-python/) – DarrylG Apr 11 '20 at 12:04
  • Great! Thank you! – JA-pythonista Apr 11 '20 at 12:15

1 Answers1

3

You missed self before calling private method.

def __init__(self, username):
    self.username = self._check_username(username)

If it is still gives error like: 'Freelancer' object has no attribute 'username' define username variable

FAHAD SIDDIQUI
  • 621
  • 4
  • 22
  • 1
    Need double underscores to make method private, otherwise it's still accessible by public i.e. `bill = Freelancer('bill'); bill._check_username('bill')` works [see](https://www.geeksforgeeks.org/private-methods-in-python/) – DarrylG Apr 11 '20 at 12:21