[Tutor] Help with OOP!

Steven D'Aprano steve at pearwood.info
Tue Nov 6 03:28:55 CET 2012


On 30/10/12 17:56, Pete wrote:
> I'm taking this class on python at UCSC. They said this list could help. I
> don't' understand OOP and I'm having a hard time understanding the "scope"
> and why the def inside class are not like function

But they are like functions. Can you explain in more detail what you don't
understand about def inside classes?


>-plus I can't get my
> c-brain around the implicit typing. It looks like the interpreter does not
> want to return a tuple. why?

I can't answer that question because I don't know why you think you can't
return a tuple. Can you show an example of it failing?


In C, you have variables, which are typed, and values. When you declare that
"n" is an int, the C compiler can tell ahead of time that any operation you
do to n will give an int or not, and prohibit you from using n to store (say)
a string.

In Python, variable names are not typed. If you consider the name "n", Python
will not prevent you from using n to store ints one moment and strings another
moment. That's a deliberate design choice, so please don't get into an
argument about it being "better" or "worse" than the way C does it. There are
pros and cons to both.

But at any specific moment, the variable name "n" will be bound to an object,
and Python always knows what the type of the object is. So if you try to do
something to n as if it were a string, but it is actually an int, Python will
know that you can't and give you an exception (instead of crashing the
computer). For example, you can convert strings to uppercase, but not ints:


py> n = "Fred"  # n for Name
py> n.upper()
'FRED'
py> n = 42
py> n.upper()
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'upper'



So the main difference in typing is that in C you get *compile-time*
type errors while in Python you get them at *run-time* instead. In both
cases, you have to write your code to avoid type errors.




-- 
Steven


More information about the Tutor mailing list