C W <tmrs...@gmail.com> writes: > I am new to OOP.
Welcome, and congratulations on learning Python. > I'm a bit confused about the following code. > > def print_time(self): Begins a function definition. The function will receive one argument (the class instance), and bind the name ‘self’ to that. > time = '6:30' Creates a new text string, and binds the name ‘time’ to that. Nothing else ever uses that local name. > print(self.time) Gets the value of ‘self.time’ – which means, get the object referred to by ‘self’, look up an attribute named ‘time’, and get the object that name is bound to – then pass that object as an argument to call ‘print’. The ‘print’ function will get a text representation of the object, and emit that text to output. Nothing else happens in the function; so, the local name ‘time’ falls out of scope and is never used. The function then returns ‘None’. > clock = Clock('5:30') > clock.print_time() > 5:30 > > I set time to 6:30 No, you bound *a* name ‘time’ locally inside the ‘print_time’ function; but you never used that afterward. The local name ‘time’ is a different reference from the ‘self.time’ reference. > How does line-by-line execution run inside a frame? How does __init__ > work? After Python creates an instance of a class (using that class's ‘__new__’ method as the constructor), it then tells the instance to initialise itself; it calls the object's ‘__init__’ method as the initialiser. So the initialiser, named ‘__init__’, is called once the object exists, but before the caller gets to use that object. The initialiser's job is to initialise the state of the object; your class does this by setting the per-instance ‘time’ attribute. So, by the time your statement binds the name ‘clock’ to the new Clock instance, that instance already has an attribute ‘clock.time’ with the value ‘'5:30'’. That attribute is then available when something else uses that object; for example, the ‘print_time’ method accesses that attribute and prints it out. -- \ “As the most participatory form of mass speech yet developed, | `\ the Internet deserves the highest protection from governmental | _o__) intrusion.” —U.S. District Court Judge Dalzell | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list