Printing all objects from a class [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I currently have a class that turns my list of lists into a list of objects, where every object has a certain amount of stuff from the constructor. Lets say they have names, and some random numbers.
What I would like to do is print all of these objects simultaneously, where each object is one line. How would I go about doing this, I tried making a Str function, but it still returns ""
Okay, I have a class which has 10 objects, these have the attributes self.planet, self.distance, self.distsquared, self.radius, self.diamater where distance/distsquared/radius/diamater are all integers and I have a function which is supposed to print all of the planets after their distance, with the furthest distance highest. But when I try to make a function return "" % (self.planet, self.distance, self.distsquared, self.radius self.diameter) it still only prints I want every object to be printed
Thanks in advance!

For a list of objects, you can print them neatly using:
print("\n".join(str(x) for x in object_list))
The class should have the function to make each object into a string as follows:
def __str__(self):
return "Attr1: {0.attr1}, Attr2: {0.attr2}, ...".format(self)

Related

python .apply calling function error [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 7 years ago.
Improve this question
def awesome_count():
if 'awesome' in dict:
return 1
else:
return 0
products['awesome']= products['word_count'].apply(awesome_count)
TypeError: awesome_count() takes no arguments (1 given)
what is the issue with calling the function. can somebody help?
Looks like your awesome_count function should take one argument, dict:
def awesome_count(dict):
....
You should really call it something besides dict though as that is a built-in data type. For something simple like this d would be fine.
Another thing to keep in mind is that Python is not javascript -- there is no apply method on dicts unless you have subclassed and added it yourself.

"randint" function working unexpectedly inside functions? [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 need to use the random.randint inside of a function, but it always returns weird results. However, when I try it outside of the function, it works perfectly.
Here's a quick function to choose a number between one and six to illustrate my point:
import random
def dice():
return random.randint(1, 7)
print(dice)
And then I get an output like:
<function dice at 0x0000000004314D90>
I would really appreciate it if you could explain what's happening and how to prevent it.
You need to call the dice function and then print the result (return value).
print(dice())
# ^^
In Python, functions are called by placing (...) after their names. If your function takes any arguments, they would go where the ... is and be separated by commas:
func(arg1, arg2)
Your current code was printing <function dice at 0x0000000004314D90> because that is the representation of the function object that you were printing.
you are simply forgetting a set of parenthesis. it should be
print(dice())
now you are printing the function object.

Class instance attributes won't seem to initialize [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This seems like such a simple question, but there don't seem to be any answers that address my particular issue, which is why the init method never actually initiates the class instance variable 'listlist'.
class PointsList():
def _init_(self):
self.listlist = [None]
def addtolist(self,item):
self.listlist.append(item)
def getlist(self):
return self.listlist
a = PointsList()
a.addtolist('Scarlet')
print a.getlist()
Running the above code gives me:
AttributeError: PointsList instance has no attribute 'listlist'
The error is traced to line 5 when the 'addtolist' method attempts to add an item to the evidently nonexistent 'listlist' instance variable.
I've checked the indentation many times but it appears to be sound. Is there something wrong with my Python installation? I am using Python v2.7.5 (haven't gotten around to 2.7.6 yet) and the Spyder IDE v2.2.0
Python special methods use two underscores at the start and end; you need to name the initializer __init__, not _init_:
class PointsList():
def __init__(self):
self.listlist = [None]
Underscore characters are usually shown connecting up forming a longer line, but there are two underscores before init, and two after.

What is a DEF function for Python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to coding Python and I just can't seem to understand what a Def function is! I have looked and read many tutorials on it and I still don't quite understand. Can somebody explain to me what it is, what I use it for, and give me some examples. For the examples please make them easy and understandable for a newb to Python. Thanks!
def isn't a function, it defines a function, and is one of the basic keywords in Python.
For example:
def square(number):
return number * number
print square(3)
Will display:
9
In the above code we can break it down as:
def - Tells python we are declaring a function
square - The name of our function
( - The beginning of our arguments for the function
number - The list of arguments (in this case just one)
) - The end of the list of arguments
: - A token to say the body of the function starts now
The following newline and indent then declare the intentation level for the rest of the function.
It is just as valid (although uncommon) to see:
def square(number): return number * number
In this case, as there is no indentation the entirety of the function (which in this case is just one line) runs until the end of line. This is uncommon in practise and not considered a good coding style.

Execute all functions from module [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
class MyClass(object):
def fn():
return 1
for i in [method for method in dir(inspect) if callable(getattr(inspect, method))]:
print i(MyClass) // Error here
Error: TypeError: 'str' object is not callable
If i change print statement to:
print "%s(MyClass)" % i
this simply print:
ArgInfo(MyClass)
and so on...
dir(module) returns a list of names (strings) defined in the module, not the actual functions or values. To get those, use getattr, which you already use for the callable check.
for name in dir(your_module):
might_be_function = getattr(your_module, name)
if callable(might_be_function):
print might_be_function(your_parameters)
Of course, it might still be the case that the function is not applicable to the given parameters, so you might want to check this first, or wrap in in a try block.
Do you need to call all methods by name like that?
class C1:
def f1(self):
print('f1---')
def f2(self):
print('f2---')
inspect = C1()
for i in [method for method in dir(inspect) if callable(getattr(inspect, method))]:
getattr(inspect, i)()

Categories