Classes

Grant Edwards invalid at invalid.invalid
Fri Oct 31 13:43:35 EDT 2014


On 2014-10-31, Seymore4Head <Seymore4Head at Hotmail.invalid> wrote:
> On Sat, 01 Nov 2014 04:06:44 +1100, Steven D'Aprano

>>Let's make the class a bit easier to use, at the expense of doing a bit more
>>work up front:
>>
>>class MyClass:
>>    def __init__(self, value, message):
>>        self.value = value
>>        self.message = message
>>
>>obj = MyClass(23.0, "hello world")
>>print(obj.value)
>>print(obj.message)
>>
>>
>>The __init__ method is automatically called when you call the class as if it
>>were a function. Because the __init__ method has two arguments (plus the
>>special "self" argument), you have to call the class with two arguments.
>>They get used as the value and message respectively.
>>
>>Or we can give it getters and setters:
>>
>>class MyClass:
>>    def set_value(self, value):
>>        self.value = value
>>    def get_value(self):
>>        return self.value
>>    def set_message(self, message):
>>        self.message = message
>>    def get_message(self):
>>        return self.message
>>
>>obj = MyClass()
>>obj.set_value(23.0)
>>obj.set_message("hello world")
>>print(obj.get_value())
>>print(obj.get_message())
>>
>>
>>If you're thinking that's a lot of extra work for not much benefit, 99.99%
>>of the time you're right.
>
> I agree it is more work.  But more work means more practice. I need
> more practice figuring out how these commands work.

Except you're practicing doing things the "wrong" way.  If you want to
learn Java, then use Java.  If you want to learn Python, then don't
write Java.

-- 
Grant Edwards               grant.b.edwards        Yow! HOORAY, Ronald!!
                                  at               Now YOU can marry LINDA
                              gmail.com            RONSTADT too!!



More information about the Python-list mailing list