Solomon Malih
Solomon Malih

Reputation: 5

How do I use a method on a class attribute in Python3?

I want to be able to use methods (such as .upper() or .lower()) on a class attribute. For example, in the code below:

class Player:
    def __init__(self, score,):
        self.score = score
        self.username = str(self)
        self.password = str((self.upper()))
        
player1 = Player(0)
print(player1.password)

I expect the print statement to print out 'PLAYER1' but instead I receive

AttributeError: 'Player' object has no attribute 'upper'

Upvotes: 0

Views: 129

Answers (3)

Aagam Sheth
Aagam Sheth

Reputation: 691

Self is a variable name that represents an instance of the class. It is a parameter to reference the current object of the class. By using it we can access the parameters and methods of the class.

The reason you need to use self is because Python does not use the @ syntax to refer to instance attributes.

Note : you can name that variable anything. But it has to be the first parameter. For example :

class Player:
    def__init__(myclassobj, score):
        myclassobj.score = score
        myclassobj.username ...
        ...
        ...

You are getting the error :

AttributeError: 'Player' object has no attribute 'upper'

because when you say self.upper, it searches for a attribute in the class instance and you have not defined any upper attribute.

In the code below:

self is an object to specify instance of the class the method. And score cannot be used with .upper as it is of integer type.

class Player:
    def __init__(self, score,):
        self.score = score
        self.username = str(score)
        self.password = str((score.upper()))
        
player1 = Player(0)
print(player1.password)

As per my understanding it should be:

class Player:
    def __init__(self, score, username, password):
        self.score = score
        self.username = str(username)
        self.password = str((password.upper()))
        
player1 = Player(0, 'ABC', 'abc@123')
print(player1.password)

Upvotes: 1

anony
anony

Reputation: 1

That's because you are calling the object itself, not the object name The upper() is a method for string so it will not on self

Upvotes: 0

Oscar916
Oscar916

Reputation: 149

You can add attributes in the class so that when the user enter their username and password. It is a string. Then you can use the .upper() method.

class Player:
    def __init__(self, username, password, score,):
        self.score = score
        self.username = username.upper()
        self.password = password.upper()
        
player1 = Player("tom", "abcd1234",0)

print(player1.username)
print(player1.password)

Output:

TOM
ABCD1234

Upvotes: 0

Related Questions