Print class object content through python function - python

I am reading some threads but i don't understand how do proceed.
I have a function and class as follow. How can I print the class content through the function?
def get_address(address):
resource = 'address/{0}?format=json'.format(address)
response = util.call_api(resource)
json_response = json.loads(response)
return Address(json_response)
class Address:
def __init__(self, a):
self.hash160 = a['hash160']
self.address = a['address']
self.n_tx = a['n_tx']
self.total_received = a['total_received']
self.total_sent = a['total_sent']
self.final_balance = a['final_balance']
self.transactions = [Transaction(tx) for tx in a['txs']]
I tried to print(get_address('*******************')), but this return the object name. Then, adding the following code to the class but it return a tuple which is throw an error. How can I print all these element correctly?
def __str__(self):
return (self.hash160,
self.address,
self.n_tx,
self.total_received,
self.total_sent,
self.final_balance,
self.transactions)

You need to either convert the entire tuple to a string:
def __str__(self):
return str((self.hash160,
self.address,
self.n_tx,
self.total_received,
self.total_sent,
self.final_balance,
self.transactions))
or you can use an f-string (or just regular string concatenation) to build your own:
def __str__(self):
return f'hash: {self.hash160}, ' +
f'address: {self.address}, ' +
...
Note that you may want to also implement __repr__(self) by having it just return str(self). Depending on how you try to output the class, this might be necessary.

__str__ needs to return a string as it's the API that declares how your class instance would be represented as a string. You could throw everything in that tuple into a dictionary and wrap it in a json.dumps() to parse it to a json string.

Related

How to create a list of instances of a given class

I'm facing problem with my code. In fact, I need to create a list of instances of my class( Patent). The name of the list is patent_ints. But when I'm trying to verify if any element in that list is a Patent one, I'm always getting a False response. And when iterating the first element is like "<__main__.Patent at 0x7f107820b710>".
Here is my code, I need help !
import json
import datetime
patent_data = json.loads(open('NASA_data.json', "r").read())
unique_center = []
for thing in patent_data["Patent_Information"]["Results"]:
for val in thing:
if(val == 'NASA Center'):
unique_center.append(thing[val])
total_num_centers = len(set(unique_center))
class Patent:
def __init__(self, abbreviated_organization_name, dict_data):
self.org_name = abbreviated_organization_name
self.title = dict_data["Title"]
# initialize instance variable called year. The value can be extracted from dict_data.
# This should be a four digit string.
self.year = str(datetime.datetime.strptime(dict_data['Date'], '%m/%d/%Y').year) #dict_data['Date'].split('/')[2]
# initialize an instance variable called month. The value can be extracted from dict_data.
# This should be a two digit string.
self.month = str(datetime.datetime.strptime(dict_data['Date'], '%m/%d/%Y').month) #dict_data['Date'].split('/')[0]
# initialize an instance variable called day. The value can be extracted from dict_data.
# This should be a two digit string.
self.day = str(datetime.datetime.strptime(dict_data['Date'], '%m/%d/%Y').day) #dict_data['Date'].split('/')[1]
self.id = dict_data['Case Number']
self.access_limit = dict_data['SRA Final']
patent_ints = [Patent(i, data) for i in unique_center for data in patent_data["Patent_Information"]["Results"]]
patent_ints[0]
Thank you in advance!
<__main__.Patent at 0x7f107820b710> is the default representation of the class when you try to print it. Add an __str__ or __repr__ method to the class and define some custom logic to return your desired details as a string:
class Patent:
def __init__(self, abbreviated_organization_name, dict_data):
...
def __repr__(self):
# return a dictionary of items in the class but you can return whatever you want
# you could do f'{self.title} {self.id} {self.year}-{self.month}-{self.day}' but str(self.__dict__) is quick to test
return str(self.__dict__)

Why does this print the memory location of an object rather than what I want?

I'm not sure what's happening when I print my dictionary.
In Python 3, I have a dictionary of parse_blast objects called transSwiss. Each object's proteinID is the key with the entire object as the value.
I can print transSwiss in it's entirety and I can also print blasto.protein, but not when I combine them to get a dictionary value. I'm not sure what is happening when I use:
print(transSwiss[blasto.protein])
<__main__.parse_blast object at 0x000000373C5666A0>
Here is the code
class parse_blast(object):
def __init__(self, line):
#Strip end-of-line and split on tabs
self.fields = line.strip("\n").split("\t")
self.transcriptId, self.isoform = self.fields[0].split("|")
self.swissStuff = self.fields[1].split("|")
self.swissProtId = self.swissStuff[3]
self.percentId = self.fields[2]
def filterblast(self):
return float(self.percentId) > 95
class parse_matrix(object):
#Consider __init__ as a Constructor
def __init__(self, matrix_lines):
(self.protein,
self.Sp_ds,
self.Sp_hs,
self.Sp_log,
self.Sp_plat) = matrix_lines.strip("\n").split("\t")
def separate_tuples(one_tuple):
return "\t".join(one_tuple)
blastmap = map(parse_blast, blast_output.readlines())
filtered = filter(parse_blast.filterblast, blastmap)
matrixmap = map(parse_matrix, matrix_output.readlines()[1:])
transSwiss = {blasto.transcriptId:blasto for blasto in filtered}
for matrixo in matrixmap:
print(transSwiss[matrixo.protein])
Because your object is defined by you, you also need to tell python how you want it to print. You can do this by defining a function called "__str__" that returns how you want to print your object.
https://en.wikibooks.org/wiki/Python_Programming/Classes#str

TypeError: Can't convert 'list' object to str implicitly

I have python class:
class Athlete:
def __init__(self,fullName,dob,times):
self.fullName = fullName
self.dob = dob
self.times = times
## print('times is ',times)
def __str__(self):
return ''.join("Athlete[fullName="+self.fullName +",dob="+self.dob+",sortedTimes="+self.sortedTimes+"]")
def __repr__(self):
return self.__str__()
Instances of this class are stored in map athleteMap as values.
When I do print(athleteMap) I get this error:
File "D:/Software/ws/python_ws/collections\athleteList.py", line 11, in __str__
return ''.join("Athlete[fullName="+self.fullName +",dob="+self.dob+",sortedTimes="+self.sortedTimes+"]")
TypeError: Can't convert 'list' object to str implicitly
I need to print Athlete instance in print method.
How to do this in python?
Convert times to a string explicitly then:
return "Athlete[fullName=" + self.fullName + ",dob=" + self.dob + ",sortedTimes=" + str(self.sortedTimes) + ']'
You don't need ''.join() here.
A better option is to use string formatting:
return "Athlete[fullName={0.fullName},dob={0.dob},sortedTimes={0.sortedTimes}]".format(self)
Your join call doesn't make sense. You probably want something like this:
def __str__(self):
return "Athlete[fullName="
+ str(self.fullName)
+ ",dob="
+ str(self.dob)
+ ",sortedTimes="
+ str(self.sortedTimes)
+ "]"
I've added str to every attribute because I can't know for sure in which one of them you put a list. The problem is evident from the error - lists can't be converted implicitly to string - you need to mark this conversion explicitly via str() call. One of your attributes (dob or times most probably) is a list.

How to intercept a specific tuple lookup in python

I'm wondering how could one create a program to detect the following cases in the code, when comparing a variable to hardcoded values, instead of using enumeration, dynamically?
class AccountType:
BBAN = '000'
IBAN = '001'
UBAN = '002'
LBAN = '003'
I would like the code to report (drop a warning into the log) in the following case:
payee_account_type = self.get_payee_account_type(rc) # '001' for ex.
if payee_account_type in ('001', '002'): # Report on unsafe lookup
print 'okay, but not sure about the codes, man'
To encourage people to use the following approach:
payee_account_type = self.get_payee_account_type(rc)
if payee_account_type in (AccountType.IBAN, AccountType.UBAN):
print 'do this for sure'
Which is much safer.
It's not a problem to verify the == and != checks like below:
if payee_account_type == '001':
print 'codes again'
By wrapping payee_account_type into a class, with the following __eq__ implemented:
class Variant:
def __init__(self, value):
self._value = value
def get_value(self):
return self._value
class AccountType:
BBAN = Variant('000')
IBAN = Variant('001')
UBAN = Variant('002')
LBAN = Variant('003')
class AccountTypeWrapper(object):
def __init__(self, account_type):
self._account_type = account_type
def __eq__(self, other):
if isinstance(other, Variant):
# Safe usage
return self._account_type == other.get_value()
# The value is hardcoded
log.warning('Unsafe comparison. Use proper enumeration object')
return self._account_type == other
But what to do with tuple lookups?
I know, I could create a convention method wrapping the lookup, where the check can be done:
if IbanUtils.account_type_in(account_type, AccountType.IBAN, AccountType.UBAN):
pass
class IbanUtils(object):
def account_type_in(self, account_type, *types_to_check):
for type in types_to_check:
if not isinstance(type, Variant):
log.warning('Unsafe usage')
return account_type in types_to_check
But it's not an option for me, because I have a lot of legacy code I cannot touch, but still need to report on.

Need to print with spaces

I have to print name with spaces, can u help me please?
I got the code like this:
class Perfil:
def __init__(self,email,nome,cidade):
self.email=email
self.nome=nome
self.cidade=cidade
def __str__(self):
return "Perfil de "+self.nome+" ""("+self.email+")"" de "+self.cidade
def getCidade(self):
return self.cidade
def setCidade(self,novo):
self.cidade=novo
def getDominio(self):
t=self.email.rpartition("#")
return t[2]
def limpaNome(self):
new=""
if self.nome.isalpha()==True:
return self.nome
else:
for i in self.nome:
if i.isalpha()==True:
new +=i
return new
When i run the program:
>>> p=Perfil("lol#mail.pt","Ze Car231los", "Porto")
>>> p.limpaNome()
'ZeCarlos'
I need a print like 'Ze Carlos' (with space)
Basically i need to wrote a program using abstract data types (class Profile) to save information for each user. Each object got the following attributes:
email
name
city
The class should have the following methods to manipulate the objects above
Method
__init__(self, email, name, city) - constructor
__str__(self)
getCity(self) - return the value of atribute city
getCity(self.new) - return the atribute city with a new value
getDomain(self) - example: lol#mail.com sugestion: use the method partition (i have to return mail.com only)
cleanName(self) - change the atribute name, deleting characters WICH are not alphabetic or spaces sugestion: use method isalpha
If all you want to do is remove all occurrences of '0','1','2',...,'9' from the string, then you could use str.translate like this:
def limpaNome(self):
return self.nome.translate({ord(c):None for c in '0123456789'})
Note that there is no need for getters/setters like this in Python:
def getCidade(self):
return self.cidade
def setCidade(self,novo):
self.cidade=novo
Instead, just let the user access/set the attribute directly: self.cidade. If, at some point, you'd like to run a function whenever the attribute is accessed or assigned to, then you can make cidade a property without having to change the usage syntax.
You could even make getDominio and limpaNome properties too:
#property
def dominio(self):
t=self.email.rpartition("#")
return t[2]
#property
def limpaNome(self):
return self.nome.translate({ord(c):None for c in '0123456789'})
Notice you don't need paretheses when accessing or setting the property. The syntax looks the same as though lipaNome were a plain attribute:
>>> p=Perfil("lol#mail.pt","Ze Car231los", "Porto")
>>> p.limpaNome
Ze Carllos
>>> p.dominio
mail.pt
import string
# ... the rest of your code
# ...
def limpaNome(self):
whitelist = set(string.ascii_uppercase+string.ascii_lowercase+" ")
if self.nome.isalpha():
return self.nome
else:
return ''.join(ch for ch in self.nome if ch in whitelist)
Or with regex:
import re
# ...
# ...
def limpaNome(self):
return re.sub(r"[^a-zA-Z ]",'',self.nome)
Note that if I were you, I'd do:
class Perfil:
def __init__(self, email, nome, cidade):
self.email = email
self.cidade = cidade
self.nome = limpaNome(nome)

Categories

Resources