Most of you must be familiar with how we can define setting and getting attributes in a class:
class Foo
def initialize(val=0)
@var = val
end
def var
return @var
end
def var=(val)
val = [[0, val].max, 100].min # Binding the value
@var = val
end
end
I would like to do the same in a Python class. What is the syntax for defining the "var=(val)" method in Python?
Tried Google yet?
In Python everything is public.
class Foo():
def __init__(self):
self.bar = 1
foobar = Foo()
print foobar.bar # will print 1
foobar.bar = 2
print foobar.bar # will print 2
Quote from: Biker WcW on May 09, 2009, 08:25:16 pm
Tried Google yet?
Yes, but I didn't know what to search for. I tried some stuff but didn't find what I need. Though, I stumbled upon the implementation in some module on the internet.
Quote from: Rival Blizzard on May 10, 2009, 06:53:34 am
In Python everything is public.
class Foo():
def __init__(self):
self.bar = 1
foobar = Foo()
print foobar.bar # will print 1
foobar.bar = 2
print foobar.bar # will print 2
Yes, but I want to have more control over setting and getting attributes.
Anyway, I kind of figured it out. The key is the
__getattr__ method. It gets called when a called attribute is not found. I guess this is resolved until furthur notice. Thanks guys :)
class Foo():
def __init__(self):
self.bar = 1
def getBar(self):
return self.bar
def setBar(self, newBar):
self.bar = newBar
Bar = property(getBar, setBar)
foobar = Foo()
print foobar.Bar # will print 1
foobar.Bar = 2
print foobar.Bar # will print 2
getBar and setBar will still be visible as well as bar outside of foo.
...he means like this, I believe:
class Foo
def initialize
@bar = nil
@state = true
end
def bar=(nbar)
@bar = nbar.size > 2 ? [nbar.first, nbar.last] : nbar
end
def bar
@state = ! @state
return @state ? @bar : [nil, nil]
end
end
Sucky example, but it shows the complexity that he might need, and it's fun :P
But he got, so it's all good. *goes off the learn some python*
That's what I did. He can use .Bar (with capital B, yes) to assign or get the variable over the set and get method. i.e.
class Foo():
def __init__(self):
self.bar = 1
def getBar(self):
return self.bar + 1
def setBar(self, newBar):
self.bar = newBar
Bar = property(getBar, setBar)
foobar = Foo()
print foobar.Bar # will print 1
foobar.Bar = foobar.Bar
print foobar.Bar # will print 2
It pretty much works like C#'s properties. Except that you can still see all the other stuff. >.<
Ooh. Python is fancy then. Sorry Blizz :(
class Foo
{
private int bar;
public Foo()
{
this.bar = 1;
}
public int Bar
{
get { return this.bar; }
set { this.bar = value; }
}
}
xD
I wonder how Obj-C does that stuff. It gain do a ton of crap from what little I've seen, and it's really Ruby-like, but the syntax is god-awful.
QuoteBar = property(getBar, setBar)
lol, I did even more reading and I came across properties just an hour ago. Gotta say, I'm starting to like Python.