want a calculation result instead of <bound method ...Python 2.8 - methods

I have tried finding this in the docs but don't quite get it. I am starting to work with Classes, When I try to get the result, I get instead of the actual 'width' I maybe I need to get but not sure.. It sounds too complicated just to get a result. Can someone advise?
I have:
class Rectangle(object):
def __init__(self, pt_ll, pt_ur):
self.ll = pt_ll
self.lr = Point(pt_ur.x, pt_ll.y)
self.ur = pt_ur
self.ul = Point(pt_ll.x, pt_ur.y)
def width(self):
"""Returns the width-float of the Rectangle."""
w = self.ur.x - self.ll.x
return w
Then I call it:
r = Rectangle(Point(0,0), Point(10,10))
print r.ur.x
print r.ll.x
print r.width
and get this output:
10.0
0.0
<bound method Rectangle.width of <__main__.Rectangle object at 0x000000000B5CBC50>>

print r.width
This returns the width method itself, this is what you see in the output.
You want to call that method so you need to instead do this:
print r.width()
This hints at an interesting thing about python, you can pass around functions just like you can with other variables.

Related

What is my method returning here?

I have a question that I've already found the solution to (or perhaps it is just chance), but I'm hoping someone can explain why it works, and what Ruby is doing being the scenes here.
I'm doing something with fixed width output text and ANSI color codes. I don't want the escaped characters to count towards my length, so I wrote a little method for the String class to calculate the length excluding the color codes:
def length_minus_codes
color_codes = [ "\033[30m",
"\033[0m" ,
"\033[31m",
"\033[32m",
"\033[33m",
"\033[34m",
"\033[35m",
"\033[36m",
"\033[37m",
"\033[40m",
"\033[41m",
"\033[42m",
"\033[43m",
"\033[44m",
"\033[45m",
"\033[46m",
"\033[47m",
"\033[1m",
"\033[22m",
"\033[7m",
"\033[27m"]
#Create new variable to strip
stripped_self = self
#loop through color code array
for index in 0 ... color_codes.size
#strip color codes from string
stripped_self.gsub!(color_codes[index],"")
end
#return variance of self to stripped self to
#get length of string not including color codes
return self.length - (self.length - stripped_self.length)
end
end
I thought it was working fine, until I realized that after it was called, the string it was called on had the character codes stripped from it.
I tried a few things, before decided to change this:
stripped_self.gsub!(color_codes[index],"")
To this:
stripped_self = stripped_self.gsub(color_codes[index],"")
Now it is working fine.
What I don't understand is why? I understand the basic concept of in place methods (!) which I was using on the gsub, but it wasn't modifying self, but rather a variable that I set in the method, and second I only want to return the length of the string, not an actual string.
Can anyone explain what is happening here?
When you do
stripped_self = self
you are simply creating a new reference to the self string object, you are not creating a new string. So any in-place modifications (by gsub! in this case) will be reflected on the self object.
If you want to create a new object that is not a reference, you need to duplicate the object:
stripped_self = self.dup
Possibly a simpler solution here is just to use the non-bang version of gsub and save that to a variable. gsub! changes the receiver as bang methods often do, gsub will simply return a modified object safely without effecting the receiver.

How to modify the value of a variable whose name is given

I wish to have a method that takes in a string, and then updates a variable with the name of that string. This is an example of my attempt:
#other_class = OtherClass.new()
def change_variable(variable_string)
self.#other_class.send.variable_string += 1
end
I am getting the error:
syntax error, unexpected tIVAR
with the pointer just before 'send' in the method above. Does anyone have any suggestions to make this work?
You probably want instance_variable_set http://ruby-doc.org/core-2.0/Object.html#method-i-instance_variable_set
The syntax using your variables is I think:
other_var = ('#' + variable_string).to_sym
#other_class.instance_variable_set( other_var, #other_class.instance_variable_get( other_var ) + 1 )
The immediate syntatic error is that you're using self and # wrongly.
Either one is fine but not in conjunction with each other.
So in your case self.other_class.send... would be fine but then you cant declare it as #.
As would # be but then you cant do self.
These are meant to do different things and these are that
# is an instance variable and so is self but the difference is that using # calls the attribute other_class directly as to where self calls the method other_class.
So # is both a getter and setter in one so you can do
#other_class = my_milk_man as to where
self.other_class -> self.other_class (as getter),
self.other_class = my_milk_man -> self.other_class= (as setter).

Tkinter Error when using Entry Delete Method

In my game, I have an __init__ function which creates a set of seven entry boxes, like so:
self.string1 = StringVal()
self.entry1 = Entry(frame, textvariable = self.string1).grid(row = 4, column = 1, sticky = W)
This is copied six more times. This works.
At the end of the game, though, I want to delete the Entry box's text, using this code I found several places online:
self.entry1.delete(0, END)
I also tried using something else I found:
if self.entry1.get():
self.entry1.delete(0, END)
These both say that self.entry1 is a NoneType object, and has no method .get() or .delete(). Just to try things out, I substituted self.entry1.get() and self.entry1.delete(0,END) with self.string1.get(), etc. I also tried substituting .delete(0, END) with .delete(0.0, END). Neither of these worked either. I do not understand what I am doing wrong.
Thanks for your help!
When you do something like this:
self.foo = Button(...).grid(...)
... Then what gets stored in self.foo is the result of the call to grid(). This will always be None. You need to separate your widget creation from the loyout in order to save a reference to the created widgets.

Change Progress Bar format to show x.x% in pyQt4

I have been trying to find out which the right syntax for the .setFormat() method of the ProgressBar is, but i cannot find any information about that. %p% just shows the percentage as '34%' but I would like to display fractions as well like this: '33.7%'.
Yes you can simply add self.pbar.setFormat('%.02f%%' % (self.step)) with your code
and if you want to implemnt more precise formating you can re implement QProgressbar like this maybe
class qProress(QtGui.QProgressBar):
"""docstring for qProress"""
def __init__(self,args):
super(qProress, self).__init__(args)
self.valueChanged.connect(self.onValueChanged)
def onValueChanged(self, value):
self.setFormat('%.02f%%' % (self.prefixFloat))
def setValue(self, value):
self.prefixFloat = value
QtGui.QProgressBar.setValue(self, int(value))

How to access attribute which are stored as variables

model Sample has attributes car,bike
x ="bike"
y = Sample.new
How can I do?
y.x ??
It gives me an error
Is there any way I can do it, I know that x is an attribute but I dont know which one.
So how can I get y.x?
You can use send to invoke a method on an object when the method is stored as a string:
x = "bike"
y = Sample.new
y.send(x) # Equivalent to y.bike
The following are equivalent, except that you may send protected methods:
object.method_name
object.send("method_name")
object.send(:method_name)
You have to use dynamic message passing. Try this:
y.send :bike
Or, in your case
y.send x

Resources