Home > Blockchain >  <__main__.User object at 0x000002C1B781D310> - python
<__main__.User object at 0x000002C1B781D310> - python

Time:11-04

Hello so im new to python and im in progress to learning class and function. I keep getting this error code, i don't know whats wrong on my code. Here is the source code:

class Data:
    def __init__(self,nama):
        self.nama=nama
    def __private(self):
        self.ganti="Replace"
    def ganti(self):
        self.prvt=self.ganti
        print(self.prvt)
class User(Data):
    def __init__(self,nama):
        self.nama=nama
        super().__init__
    def printUsername(nama):
        print(nama)

user1 = User("Test")
user1.printUsername()
user1.ganti()
user1.printUsername()

When i run, the output is like this:

<__main__.User object at 0x000002C1B781D310>
<bound method Data.ganti of <__main__.User object at 0x000002C1B781D310>>
<__main__.User object at 0x000002C1B781D310>
Press any key to continue . . .

So whats wrong on my code? I excpeted the output is:

Test
Replace

CodePudding user response:

You have some Syntax error in your code.

  • Variable name and function name shouldn't be the same.
  • When a variable is defined in init, all functions use it and there is no need to redefine it. Even when a class inherits from another class.

This code will print the output you want.

class Data:
    def __init__(self, nama):
        self.nama = nama
        self.ganti = "Replace"
        self.prvt = self.ganti

    def Ganti(self):
        print(self.prvt)

    def __private(self):
        pass


class User(Data):
    """
    def __init__(self):
        super().__init__()
        # because we don't have new variable to define, we can remove this function.
    """
    
    def printUsername(self):
        print(self.nama)


User('Test').printUsername()
User('Test').Ganti()
  • Related