Search code examples
pythonclassoopmember

Accessing member variable in Python?


I have recently started learning python (coming from C++ background), but I could not understand how should I access the member variable (nonce) and use it in the second function called def mine_block().Aren't all members of the class Block publicly available from everywhere?

class Block:
    '''
    Дефинираме ф-я , която създава
    променливите като членове на класа Block
    '''
    def _init_(self,prevHash,index,nonce,data,hash,time):
        self.prevHash = prevHash
        self.index = index
        self.nonce = nonce
        self.data = data
        self.hash = hash
        self.time = time

    def get_hash(self):
        print(self.hash)

    def mine_block(self,difficulty):
        arr = []
        for i in range(difficulty):
            arr[i] = '0'
        arr[difficulty] = '\0'
        str = arr
    while True:
        '''
        here I receive an error
        unresolved referene nonce
        '''
        nonce++

Solution

  • To refer to class attributes within the class methods you need pass the object itself into the methods with the keyword self. Then you can access other class methods and the class attributes with self.foo.

    Also, the while True loop should not be indented at root level within the class. Last, the foo++ C-style is not correct in Pyhton, it should be foo += 1