"modules, classes, and objects" lpthw

@zedshaw, I really like so far your discussion on OOP. Spent a lot of “…huh?” time on this topic elsewhere.

Anyway, you state on p 183

“2. Python crafts an empty object with all the functions you’ve specifed in the class using def”

My question is: it doesn’t have to be in a defined function to be assigned to the object, though, right?

For example:


class myClass(object):
    def f():
        print 'this gets called by the object'
    s = 'as does this'

Just curious, what is “s” is it a class variable or an instance variable?

I don’t know. When I do this:

class MyClass(object):
    s = 'this is s sans function'
    print(s)
    def __init__(self):
        self.s = 'this s is inside function'
        print(self.s)
this is s sans function # this prints without an object. Would that make
# it a class variable, since it is called without an object?

y = MyClass()
this s is inside function # what is interesting here is that I didn't have
# to call the object. Just creating the object initiated the class function. 
# So I really don't know what is happening here. But it is interesting....

The s is going to be a class variable (attribute), and you should be able to get to it like this:

MyClass.s

or

y = MyClass()
y.s

But, that attribute should be shared among all the classes, so what you’re doing by using self.s is only accessing the s in your object. Try this (off the top of my head):

print(y.s, MyClass.s)

They should be different, but let me know if they’re not and I can come up with a different demo.

Given the above, with

s = 'class variable'

and

self.s = 'instance variable'
>>> o = MyClass
>>> p = MyClass()
>>> print(o.s, p.s, MyClass.s)
class variable instance variable class variable
1 Like

Yes see the difference? When it is on the class, then that should be available to all of the objects. When it’s on an individual object it should only be on that one object. Now the next thing is you really shouldn’t be shadowing variables between the object and the class. This is caused a lot of confusion.

1 Like

Hi, I was trying to understand self and init but this line

“Python crafts an empty object with all the functions you’ve specifed in the class using def”

s not in lp2thw edition I have - is it in lp3thw?

Am not sure I understand, but the code I posted using s is mine.

It’s in there somewhere. I believe a video I walk through how Python makes an object.

LOL ok so you meant “is” and not “s”…

Hmm, I have never once watched any of the video’s, maybe that’s where I’m going wrong at times

Definitely watch the videos. Especially with the new book, the videos are way better. Higher-quality, more content, initially a lot more interactive things like breaking code fixing it errors etc.