Classes

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Oct 31 18:06:44 CET 2014


Seymore4Head wrote:

> Because the topic of that lesson was getter setter.
> I can construct an __init___  but I was practicing get/set.

What lesson is that? Using getters/setters is discouraged in Python.

> This stuff is coming to me slowly.  I need to rinse and repeat quite a
> few more times, before I follow what is going on.

Start with the simplest class possible:

class MyClass:
    pass

Right now, that class has a name, "MyClass", no methods, and no data. But we
can still create an instance. Call the class, as if it were a function, to
create the instance:

obj = MyClass()

What's the relationship between instances and classes? Classes are a general
type of entity, instances are a specific example of that entity. You can
have many instances from a class. So:

Class: Dog
Instances: Rin-Tin-Tin, Lassie, Hooch (from the "Turner and Hooch" movie),
           Marmaduke, Gaspode the Wonder Dog, Spike the Bulldog, etc.

Class: Wizard
Instances: Gandalf, Dumbledore, the Wizard of Oz, Rincewind, etc.

Class: int
Instances: 0, 1, 2, -5, 23, 19874023, etc.


You can confirm that obj is now an instance of MyClass:

print(isinstance(obj, MyClass))

will print True.

What can you do with obj? It has no interesting methods, and no data. But we
can give it some! Python, unlike some languages, allows you to dynamically
add data attributes to instances on the fly, without pre-defining them.

obj.value = 23.0
obj.message = "hello world!"
print(obj.value)
print(obj.message)


will associate the data 23.0 and "hello world" to the attributes "value"
and "message" of the instance obj.

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.


-- 
Steven




More information about the Python-list mailing list