. .


PY 4U 48: Initializing a Python Object

February 27, 2014 8:53:52.197

Today's Python 4 You looks at how you customize the initialization of a new instance in Python. If you have trouble viewing it here in the browser, you can also navigate directly to YouTube. To watch now, click on the image below:

Object Initialization

If you have trouble viewing that directly, you can click here to download the video directly. If you need the video in a Windows Media format, then download that here.

You can also watch it on YouTube:

Tags: ,

[py4u48-iPhone.m4v ( Size: 1917965 )]

posted by James Robertson


Re: PY 4U 48: Initializing a Python Object

[peter] February 28, 2014 7:45:01.318

It took me a while to get my head around Python objects -and I hadn't been spoiled by the pleasures of Smalltalk!

1. You certainly DON'T need to bind methods to variables before you call them. That would be horrible!

your code

func = cls.world


..does the same thing as


[aside: imo your choice of the variable name cls is confusing (because you hold an instance not a class 'in' that variable called cls) but it isn't an error of course. ]


The line that reads..

i = 123

is also not an error -but I note that you refer to i (in the previous video) as an "instance variable". Actually it is a class variable. [whereas the variable called data *is* an instance variable -because it bound with self.data = ]

Eg. One might ask "what would happen if I also had i = 456 inside the __init__ method?" Answer: some_hello_instance.i would return 456 *but* the 123 would not have been mutated. Instead, you would have a class AND instance variable with the same name and the instance variable would have precedence. If you really wanted the class level i you could still refer to some_hello_instance.__class__.i [aside: Stylistically, I would move i = 123 up so it was directly under the class statement to remind me it was a class variable]

I figure that Python looks like Java but works more like Smalltalk. When a java-head looks at a Python class they *think* they are looking at a declaration, but they are not. class is just a statement that runs at "import time".

I'm guessing that Python classes would make a bit more sense to a Smalltalker because you are used to the idea that a class is an object that is created by the execution of code. The difference of course is that "Smalltalk don't need no stinkin 'import time'" (and a Pythonista would say "we don't need no stinkin image" :-> )

I guess you could say that Python builds an image on the fly whenever you run (or import) code. If only the Python IDE's worked with this image, instead of slavishly pretending to be static language tools!

Whoa, you got me monologuing there!

Looking forward to you doing "Smalltalk 4 U Pythonistas" some day :-)

 Share Tweet This