Maybe one day will shall say "there was a time where people believed in OO, hahaha what a bunch of losers, now we know that the right thing to do is.... (name your methodology)".
But in the meantime OO is better than Hashtables.
Minimalistic class:
class Pippo: name = "hello"
Unlike in Java, this doesn't work:
class Pippo:
there MUST be something inside a class.
Now you can do:
a = Pippo()
this is valid because Pippo has been defined.... if you do
a = Peppo()
you get an error because Peppo class is not defined.
If you do:
a = Pippo()
print a.name
hello
as expected, name was initialized and it's a Object variable, not a Class variable (I mean, it's not static):
a = Pippo()
b = Pippo()
a.name ="bla"
b.name = "mumble"
print a.name
bla
print b.name
mumble
Now let's do:
a.name = "ciao"
a.surname = "bello"
print a
print a.name
ciao
print a.surname
bello
so it's not necessary to declare a member of a class in order to use it. I don't like it, very error prone. I am VERY much in favor of VERY strict syntax.
So it's a MUCH better approach to use mainly Constructors to assign values to attributes:
class Pippo: def __init__(self, name, surname): self.name = name self.surname = surname
a = Pippo("alfa", "beta")
print a.name
alfa
print a.surname
beta
now you can define your classes in a module myclasses.py and then do:
from myclasses import Pippo
No comments:
Post a Comment