Python coming from Java/C++: Classes from 1000 feet, help
Ok, I'm learning Python and am trying to understand how classes work in Python. I'm coming from a C++/Java background, so if my questions are worded strangely, that should explain why. Here's what I want to know:
0. Does the term "attribute" mean methods *and* ... umm... "data attributes"? (Not sure if I'm asking that correctly.) 1. Are all attributes "public"? 2. Are there "class" attributes as well as "instance" attributes? 3. How do I declare my instance/class variables? 4. Does "data attribute" mean the same thing as "attribute"? _ _ _ _4.a. Are all methods attributes? 5. Do I *have* to define an __init__ method? Why? Thanks! |
Re: Python coming from Java/C++: Classes from 1000 feet, help
Quote:
Quote:
Quote:
Quote:
Quote:
Code:
>>> class A: Quote:
Quote:
|
Thanks Strike!
Ok. So all attributes are "public", and even though you can use _oneUnderscore or __twoUnderscores, the language does not enforce any sort of "protected" or "private" access privileges. And also: class methods/fields <--> unbound methods/attributes instance methods/fields <--> bound methods/attributes Got it. Though, I still don't get one thing you wrote: Code:
>>> class A: attribute? If so, then Code:
foo = A() A.y ahead-of-time (that is, inside bound methods of A, of course) if you're defining A.y on-the-fly in your program code like that? You're still using them to store the state of an object, no? It's like you're inventing them as needed, without regard for the methods that have to work on them... (?) |
Quote:
Code:
>>> class A: |
That's one of the most confusing things coming from a compiled language to an interpreted language like python. The variables can be created on the fly at any point, and as long as you make sure that they exist by the time you call the method, it'll work.
|
Strike wrote:
They can't make use of A.y ahead of time, because A.y doesn't exist. :) It's bound simply to that instance, and not to the class at all. Ah. That's a new concept to me: A bound data attribute -- but instead of one being bound to every object you produce from a given class, it's just a single unique attribute only bound to one specific object. I see what you mean now, and also that it's probably a kinda' less-often-used thing, though still somewhat instructive. You generally won't do this, though. The normal way you see bound variables defined is in the __init__ methods. Ahhhhh. Ok. Now we're cookin'. So, if you're careful to write your __init__() method before all others (which I'm guessing is customary), you can have all your bound data attributes ready and waiting for any methods that will later be using them. Sweet. p-static wrote: The variables can be created on the fly at any point, and as long as you make sure that they exist by the time you call the method, it'll work. Sounds like regular fly-by-the-seat-of-your-pants programming! :) Thanks for the replies. |
All times are GMT -5. The time now is 05:28 PM. |