How to access a private attribute in a class?

Asked

Viewed 477 times

0

Write a program of banks you own:

Uma classe Banco com os atributos
- private total
- public TaxaReserva
- private reservaExigida

E métodos
- public podeFazerEmprestimo(valor) --> bool
- public MudaTotal(valor)

And a class has attributes - private balance - private ID - private password

E métodos
- public deposito(senha, valor)
- public saque(senha, valor)
- public podeReceberEmprestimo(valor) --> bool
- public saldo --> float

Solution:

        class Banco(object):
    __total =10000
    TaxaReserva = 0.1
    __reservaExigida = __total*TaxaReserva
    def podeFazerEmprestimo(self,valor):
        if self.__saldo >= 1000:
            return True

    def MudaTotal(self,valor):
        Banco.__total += valor
        return Banco.__total





class Conta(Banco):
    def __init__(self,saldo,ID,senha):

        self.__saldo = saldo
        self.__ID = ID
        self.__senha = senha

    def deposito(self,senha, valor):
        Conta.__saldo += valor

    def saque(self,senha, valor):
        if (senha == self.__senha) and (valor <= self.__saldo) :
            self.__saldo -= valor
    def podeReceberEmprestimo(self,valor):
        pass

    def saldo(self):
        return self.__saldo

##    def __call__(self,x):  # torna a instância callable!
##        return x




itau = Conta(1000,123456,"POO")
itau.saque("POO",200)
print(itau.saldo())
#print(callable(itau)) #é instancia! não é callable! exceto se criar  __call__
#print(callable(Conta))# é callable!
#print(callable(itau)) se criar o def __call___, torna-se callable!
print(Banco.total) 

Tau = Account(1000,123456,"OOP") Tau.saque("POO",200)

How to access password attribute? I get error:

AttributeError: type object 'Conta' has no attribute '_Conta__senha'
  • 2

    trial def saque(self, senha, valor):, https://answall.com/q/176543/5749

  • "Python is not Java": avoid using "private" attributes with prefix "": they will only complicate your life. In terms of language all attributes are public - you can use a single "" for pointers to users of their classes (this is other programmers who will use the same) that the attributes are private, and this is done by convention. The use of "_" activates a name-mangling feature that actually has quite restricted usefulness.

  • @jsbueno: thanks! I did it just to understand how it works! Thanks for the tip!

2 answers

3

Hello,

Change your withdrawal method. Change Account by self:

def saque(self,senha, valor):
    if (senha == self.__senha) and (valor <= self.__saldo) :
        self.__saldo -= valor
  • could you explain? I don’t quite understand why!

  • Sure! This is a method that changes the attributes of the object itself (that’s why you use the self). "Account" is just the name of your class, while the self is the object that called this method (object "Itau" in your case)

  • now the error is in Banco.total, which is private: "Attributeerror: type Object 'Banco' has no attribute 'total'"

0


class Banco(object):
    __total =10000
    TaxaReserva = 0.1
    __reservaExigida = __total*TaxaReserva
    def podeFazerEmprestimo(self,valor):
        if self.__saldo >= 1000:
            return True

    def MudaTotal(self,valor):
        Banco.__total += valor
        return Banco.__total

    def get_total(self):
        return Banco.__total





class Conta(Banco):
    def __init__(self,saldo,ID,senha):

        self.__saldo = saldo
        self.__ID = ID
        self.__senha = senha

    def deposito(self,senha, valor):
        Conta.__saldo += valor

    def saque(self,senha, valor):
        if (senha == self.__senha) and (valor <= self.__saldo) :
            self.__saldo -= valor
    def podeReceberEmprestimo(self,valor):
        pass

    def saldo(self):
        return self.__saldo

##    def __call__(self,x):  # torna a instância callable!
##        return x


itau = Conta(1000,123456,"POO")
itau.saque("POO",200)
print(itau.saldo())
#print(callable(itau)) #é instancia! não é callable! exceto se criar  __call__
#print(callable(Conta))# é callable!
#print(callable(itau)) se criar o def __call___, torna-se callable!
#print(Banco.total) # da erro
print(Banco._Banco__total) #acessar variaveis privadas em Python através da sintaxe _NomeDaClasse__nomeDaVariavel
print("Total",itau.get_total())

Browser other questions tagged

You are not signed in. Login or sign up in order to post.