Why does python keep complaining that my constructor is sent one too few arguments? [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have the following class:
class Gene(object):
"""
Represents transcripts.
Called gene for convenience, but the class actually represents different transcripts of genes.
"""
def _set_start_end(strand, start_position, end_position):
if strand == '-':
return end_position, start_position
else:
return start_position, end_position
def __init__(self, transcript_name, gene_name, chromosome, strand, start_position, end_position):
self.transcript_name = transcript_name
self.gene_name = gene_name
self.chromosome = chromosome
self.strand = strand
self.start_position, self.end_position = _get_start_end(strand, start_position, end_position)
When I try to instantiate this class with refgene = Gene("NM_016166", "PIAS1", "Chr15", "-" "68346571", "68480404"), Python keeps complaining that I have one argument too few:
Traceback (most recent call last):
refgene = Gene("NM_016166", "PIAS1", "Chr15", "-" "68346571", "68480404")
TypeError: __init__() takes exactly 7 arguments (6 given)
Why? I am surely not mean to send self to the constructor?
Ps. Python 2.7.8 :: Anaconda 2.0.0 (64-bit)

You missed a comma:
Gene("NM_016166", "PIAS1", "Chr15", "-" "68346571", "68480404"),
# ^
Making that one string as Python concatenates two strings separated only by whitespace:
>>> 'foo' 'bar'
'foobar'
Add in the comma:
Gene("NM_016166", "PIAS1", "Chr15", "-", "68346571", "68480404"),
Next problem is that your _set_start_end function is not going to work; you either need to make it a method, or move it out of the class. If it is a method, you need to add self in two places; one to call it and one to receive the bound instance:
self.start_position, self.end_position = self._get_start_end(strand, start_position, end_position)
and:
def _set_start_end(self, strand, start_position, end_position):

Related

"def" bringing the wrong answer [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I made a class with some functions:
But when I instantiate the values the answer is bringing me 'alimentos', but that's wrong it should be 'portugues' .
I have two dictionaries and this class:
professores_x = {
'alimentos': [{"prof_id":"xx_alimento_1", "prof_disc":"alimentos"},
{"prof_id":"xx_alimento_2", "prof_disc":"alimentos"}],
'português': [{"prof_id":"xx_port_1", "prof_disc":"português"},
{"prof_id":"xx_port_2", "prof_disc":"português"}]}
courses_x = {'alimentos': [{"course_name":"padeiro_confeiteiro"},
{"course_name":"padeiro_confeiteiro"}]}
# trying refactoring
class Disciplinas_cursos_1:
"Define the disciplinas and professors"
def __init__(self,cursos_,professores_):
self.cursos_ = cursos_
self.professores_ = professores_
for self.p in self.cursos_.keys():
if self.p == 'alimentos': self.alimentos()
elif self.p == 'português': self.portugues()
def alimentos(self):
profiel_prof_disc = self.professores_[self.p][::]
prof_disc_al = self.p
discipl_alimentos = [self.p,[x['prof_id'] for x in profiel_prof_disc
if x['prof_disc'] == prof_disc_al]]
return discipl_alimentos
def portugues(self):
print("Now its portuguese turn")
profiel_prof_disc = self.professores_[self.p][::]
prof_disc_port = self.p
print(f"see I'm printing {prof_disc_port}. It's that the same of portuguese? If' not it's wrong")
discipl_port =[self.p,[x['prof_id'] for x in profiel_prof_disc if x['prof_disc'] ==prof_disc_port]]
print(f"see I'm printing {prof_disc_port} and {discipl_port}")
return discipl_port
# ok!! Now I do the instance:
disc_a = Disciplinas_cursos_1(courses_x, professores_x)
disc_a.alimentos()
Output
['alimentos', ['xx_alimento_1', 'xx_alimento_2']]
Nice, that is what I want but when I try the second function it's bring me 'alimentos'
but I need 'portugues' and not 'alimentos'.
disc_a.portugues()
Output
Now its portuguese turn
see I'm printing alimentos. It's that the same of portuguese? If' not it's wrong
see I'm printing alimentos and ['alimentos', ['xx_alimento_1', 'xx_alimento_2']]
Your issue is with self.p. In __init__, you're setting that value with your loop, and when you call self.alimentos() or self.portugues() in the body of the loop it will make sense since the self.p value will correspond to the method being called.
But if you call disc_a.portugues() from outside of __init__, you're going to get the last value self.p had after the loop, which may not match up at all with the method you're calling. That's why you're getting invalid output, it's using an inappropriate self.p key.
I don't have a firm understanding of what you're intending to do in your methods, so I don't really have a recommended fix. But in general, I'd suggest you think more carefully about which values you're passing to which parts of your code as attributes and as arguments. self.p should probably not exist as an attribute. Maybe it should be an argument to the methods? Maybe you need different attributes to sort your data into separate containers, rather than repeatedly looping over it all. You may need to redesign your class to have its data make more sense the way you need to use it.

How can I get the length of a string to return back? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Trying to create a function that takes in one parameter named 'dna_seq' and it should return the number of characters in that string. Once it does that it's supposed to in return say "The provided DNA sequence contains x bases"
I've tried len() but that doesn't seem to do it? It returns none
For example, it should look like this:
>dna = 'GACCGGGTGTACATACACCCCTTCCACCTC'
>> seq_len(DNA)
>>>30
Instead, it returns saying None.
# 2.
def seq_len(dna_seq):
''' add function description here '''
seq_len.len('')
# 3.
# your code here.
print('The provided DNA sequence contains', seq_len, 'bases')
You would need to return the number of characters in the string.
def seq_len(dna_seq):
return len(dna_seq)
Then you could print out:
print('The provided DNA sequence contains ', seq_len("string"), ' bases.')
Learn about void functions vs functions with return statements: https://www.youtube.com/watch?v=9Os0o3wzS_I
Void function:
>>> def function(param):
... print('Function started.')
... param*10
...
>>> x = function(5)
Function started.
>>> print(x)
None
The function above does the calculation 5*10 when you call it during the assignment statement, but x will equal to None because you did not state what value the function should output or "return".
Function with a return statement:
>>> def function(param):
... print('Function started.')
... return param*10
...
>>> x = function(5)
Function started.
>>> print(x)
50
Tip: Functions don't always have to have return functions. For example, you could have a function that prints out a string when called. But you need a return statement when you need it to output a value.
The function
def seq_len(dna_seq):
print('The provided DNA sequence contains', len(dna_seq), 'bases')
Then you can call the function
dna = 'GACCGGGTGTACATACACCCCTTCCACCTC'
seq_len(dna) #result 'The provided DNA sequence contains', 30, 'bases'

class instance not printing input argument [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have the below class and want to create a create an instance of it and print it's content:
from datetime import datetime
class Resultado:
def __init__(self, jugador, fecha, puntos = 0):
self.jugador = jugador
self.fecha = datetime.now()
self.puntos = puntos
def imprimir(self):
return str(self.fecha) + " " + self.jugador + " " + str(self.puntos)
resultado = Resultado("Andrei", 27)
print(resultado.imprimir())
But when I run it I get 0 points instead of 27:
2020-08-06 12:05:44.978692 Andrei 0
What I'm doing wrong here?
In your __init__ method, there are three arguments that you can pass while instantiating an instance of the class. These arguments are:
jugador,
fecha,
puntos.
When you instantiate your object using resultado = Resultado("Andrei", 27), it only provides two arguments. The arguments are passed in the same order as they are defined in the __init__ method, therefore you have "Andrei" in the jugador argument and 27 in the fecha argument. If you didn't have a a default value of the puntos variable defined as 0, it would give you an error. However, you did define the default value, so it gives the argument its default value.
Now, since you don't use the fecha argument, you don't actually need it and the definition of your __init__ method can look like this:
def __init__(self, jugador, puntos = 0):
self.jugador = jugador
self.fecha = datetime.now()
self.puntos = puntos
When you instantiate the object now and call your method imprimir(), it should give you the result you expect.
Note, that if you want to print your object, you can use the inherited method __str__ of the Object class. You can do it like this:
def __str__(self):
return str(self.fecha) + " " + self.jugador + " " + str(self.puntos)
And then you can just use print(resultado) to get the same result.
Also, as of Python 3.6, you can use f-strings, that are easier to work with, so you can write your output as:
return f"{self.fecha} {self.jugador} {self.puntos}"
You did not pass in a value for "puntos" so it is using the default that you provided, which is 0.
I think you do not want "fecha" to be a parameter to init since you are not using it.
Call it like this:
resultado = Resultado("Andrei", puntos=27)

Having the 'Tuple' has no attribute k [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
So I created a set of libraries that makes it easier for me to track my LoL Stats over the course of the season, for that I have a class game:
class game:
def __init__(self,kills,deaths,assists,pos,champ,cs,tk,wl,length = time(0,20,0)):
self.k = kills
self.a = assists
self.d = deaths
self.l = length
self.p = pos
self.c = champ
self.cs = cs
self.tk = tk
self.wl = wl
and a class gl (GameList)
class gl:
def __init__(self):
self.ki = []
self.ass = []
self.de = []
self.ch = []
self.po = []
self.le = []
self.csc = []
self.tki = []
self.wil =[]
Now when I use the method self.add() in the gl class where g is an object of the class game:
def add(self,g):
self.ki.append(g.k)
self.ass.append(g.a)
self.de.append(g.d)
self.ch.append(g.c)
self.po.append(g.p)
l = g.l.traM()
self.le.append(l)
self.csc.append(g.cs)
self.tki.append(g.tk)
if game.wl == True:
self.wil.append("Win")
else:
self.wil.append("Loss")
I get the Error: AttributeError: 'tuple' object has no attribute 'k'
Now when I tried this earlier it worked fine and I have no Idea why it stopped working the only thing that change was that I installed matplotlib and used that to create a few methods involving piecharts.
I would be happy if someone could help me out and maybe provide a solution, since I am fairly new to python but programmed in Pascal before.
Since you're new to Python, if you haven't already met type() let me introduce you :-) The type() function will show you what something is. To troubleshoot your code try adding some print statements like this:
def add(self,g):
print('add() type(g)={}'.format(type(g)))
print('add() g={}'.format(g))
self.ki.append(g.k)
self.ass.append(g.a)
self.de.append(g.d)
Once you find out what kind of thing g is go ahead and edit your question and let us know. Like #Graipher says it is probably something different than you expect.
Once you get that working, from a design point of view it seems easier to keep a list of Game instances instead of a list of all the individual attributes.
class gl2:
def __init__(self):
self.games = [ ] # list to hold games
def __str__(self):
return 'gl2(#games={})'.format(len(self.games)))
def add(self, g):
self.games.add(g)
Adding __str__() methods can make it much easier to see what your classes are doing. You might want to add one to your game class, if nothing else just to make debugging easier:
class game:
def __str__(self):
return 'game(#kills={})'.format(len(self.k)))

Can you use strings in classes [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Can you use strings in classes?
For my computer science project I need to use strings in my object, but I am unable to
For simplicity here is an example:
class test:
def __init__(self,string,integer):
string = self.string
integer = self.integer
string = 'hi'
integer = 4
variable = test(string, integer)
When I run this I get an error since the variable string is a string
My question is, is there a way to use strings in classes
You've got it backwards:
class test:
def __init__(self,string,integer):
self.string = string
self.integer = integer
string = 'hi'
integer = 4
variable = test(string, integer)
Your problem is not with string, it's with not getting what "self." means. What you want is:
class Test(object):
def __init__(self, string, integer):
# here 'string' is the parameter variable,
# 'self' is the current Test instance.
# ATM 'self' doesn't yet have a 'self.string'
# attribute so we create it by assigning 'string'
# to 'self.string'.
self.string = string
# and from now on we can refer to this Test instance's
# 'string' attribute as 'self.string' from within Test methods
# and as 'varname.string' from the outside world.
# same thing here...
self.integer = integer
var = Test("foo", 42)
I just had the __init__ part mixed up. It should be:
self.string = string
not:
string = self.string

Categories

Resources