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.
Related
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 am using an API library that has the following implementaion of C code to the position and rotation in a Python program:
class struct_LinmathPose(Structure):
pass
struct_LinmathPose.__slots__ = [
'Pos',
'Rot',
]
struct_LinmathPose._fields_ = [
('Pos', LinmathPoint3d),
('Rot', LinmathQuat),
]
And one of the variables is of this class. How can I get and access for example the position of this variable? LinmathPoint3d and LinmathQuat are C codes.
__slots__ (which doesn't actually work as you wrote it; it's making an unused class attribute, not actually defining slots) and _fields_ just declare variables by string name. For _fields_ said variables are default initialized if they're not passed to the constructor; for __slots__ they're empty until assigned. Either way, accessing them is like any other variable; you have an instance of the class, and you do .Pos or the like:
pose = struct_LinmathPose()
pose.Pos # Reads the attribute
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)
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
In python, I can do something like this:
# say.py
class Speaker:
def speak(self,word):
pass
def Do(self):
self.speak("hello")
Speaker().Do()
If I run this, it would do nothing at all. I can do this in another module:
import say
class Test(say.Speaker):
def speak(self,word):
print(word)
Test().Do()
If I run this, the original speak function in say.py is overwritten completely since I inherited it when I did:
class Test(say.Speaker)
So when I run the script, it will print the word rather than doing nothing. I want the name of the script to dynamically change file names without having to edit say.rb.
If I ran say.py and did:
Speaker().do()
nothing happens, but when I run the other py module, and have it do:
Test.Do()
it is overwritten since I inherited it, and changed the function of speak. Doing Speaker().Do() as it is does nothing, but if I do Test.Do(), it does work because of the override.
Is their a ruby equivalent for what I did in python, and if so, how would I do it?
It is very similar. Here's 'say.rb':
module Say
class Speaker
def speak(word) end
def Do() speak("Hello") end
end
end
In your other module:
require 'say'
class Test < Say::Speaker
def speak(word)
puts(word)
end
end
To demonstrate:
Test.new.Do
Of course there is. What have you tried that didn't work? Read up on inheritance in Ruby.
You'd literally need only change a few characters in that Python to get it to work in Ruby.
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.
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)()