When iterating a list in a python loop, why is returned element a tuple? [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 2 years ago.
Improve this question
In looping though elements in a python list, I've discovered that it is returning single-valued tuples rather than the underlying values themselves. I'm using Python 3.7.7 to run the following:
class MyClass:
def __init__(self, value):
""" class constructor """
self.value = value,
def __repr__(self):
""" class repr method """
return f'{self.__class__.__name__}(value={self.value!r})'
for val in [14, 20, 21, 48]:
_myclass = MyClass(val)
print(_myclass.value)
Which produces the following output:
(14,)
(20,)
(21,)
(48,)
It is clear that it is passing a single-element tuple to my class constructor instead of the underlying value from the list. I can see the same behavior when I pass the the objects to the print statement:
for val in [14, 20, 21, 48]:
_myclass = MyClass(val)
print(_myclass)
Which produces:
MyClass(value=(14,))
MyClass(value=(20,))
MyClass(value=(21,))
MyClass(value=(48,))
This becomes a problem when I want to work with the value in my class -- in this case, treating it as the expected number (e.g., if value < 30: value = 30) would produce a TypeError. How can I correct this?

you put , near the self.value = value remove it will fine. (Someone mentioned in the comment)
class MyClass:
def __init__(self, value):
""" class constructor """
self.value = value
def __repr__(self):
""" class repr method """
return f'{self.__class__.__name__}(value={self.value!r})'
for val in [14, 20, 21, 48]:
_myclass = MyClass(val)
print(_myclass.value)
# output
# 14
# 20
# 21
# 48

Related

Sum of items of a class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed yesterday.
Improve this question
What I have to do is to create a class that counts from a giving single argument and itself make the arithmetical operation.
class Counts:
def __init__(self, value=0):
self.value = value
def newvalue(self, other):
return Counts(self.value + other)
But for every I make to the code I got any different error, either syntax or callable argument.
The idea is to get
Counts()
Expected output
0
Next
Counts.newvalue(10)
Expected output
10
Next
Counts.newvalue(40)
Expected output
50
Next
Counts.newvalue(-17)
Expected output
33
And so on.
The code that shows the expected behaviour is
class Counts:
value = 0
def __new__(self):
return self.value
#classmethod
def newvalue(cls, other):
cls.value += other
return cls.value
however this is a somewhat strange piece of code, as you are creating a class that returns a value when initialized instead of an object deriving from that class by overriding __new__, which is pretty non-standard.
also if you want to zero the value whenever Count() is called, you can add a self.value = 0 before the return self.value
Tests ->
print(Counts())
print(Counts.newvalue(10))
print(Counts.newvalue(40))
print(Counts.newvalue(-17))
returns
0
10
50
33

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)

How to change value dict out class [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 2 years ago.
Improve this question
I want to change dict value, but allert me a Error 'object does not support item assignment'
Full Code:
def __init__(self):
self.dict = dict()
def __getitem__(self, item):
return self.dict[item]
arr = SparseArray()
arr[0] = 1```
You to override __setitem__
def __setitem__(self, key, value):
self.dict[key] = value
Then you'll be able to assign a value using an index
# use of __setitem__
arr[0] = 1
arr["foo"] = 5
# use of __getitem__
print(arr[0]) # 1
print(arr["foo"]) # 5
Also avoid naming variable as built-in name like dict, at least you can use items or values if there is no real sense about the variable's content

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

Why does python keep complaining that my constructor is sent one too few arguments? [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
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):

Categories

Resources