Re: newbie question re classes and self
On Tuesday, March 28, 2017 at 3:09:45 AM UTC-5, loial wrote: > Can I pass self(or all its variables) to a class? > Basically, how do I make all the variables defined in self > in the calling python script available to the python class > I want to call? Your question, as presented, is difficult to understand, and the phrase "variables defined in self", is quite absurd. I'm making a wild assumption here, but perhaps you want to "bulk-set" or "bulk-query" all the attributes of a class instance externally? If so, depending on how the object was defined, there are a few ways to achieve this. However, my advanced powers of perception tell me that you might be using Python in an incorrect manner, but i cannot be sure until you explain this problem in more detail. So if you can provide us a simple code example, or even psuedo code, that would be very helpful. -- https://mail.python.org/mailman/listinfo/python-list
Re: newbie question re classes and self
On 3/28/2017 4:09 AM, loial wrote: Can I pass self(or all its variables) to a class? In Python, every argument to every function is an instance of some class. The function can access any attribute of the arguments it receives with arg.attribute. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: newbie question re classes and self
loial wrote: > Can I pass self(or all its variables) to a class? > > Basically, how do I make all the variables defined in self in the calling > python script available to the python class I want to call? Inside a method you can access attributes of an instance as self.whatever: >>> class A: ... def foo(self): ... self.bar = 42 ... def baz(self): ... print(self.bar) ... >>> a = A() >>> a.baz() # bar attribute not yet set Traceback (most recent call last): File "", line 1, in File "", line 5, in baz AttributeError: 'A' object has no attribute 'bar' >>> a.foo() # sets bar >>> a.baz() # successfully print the newly created bar attribute 42 The class itself has no access to bar. In the rare case where you want to share data between instances you can use a class attribute: >>> class B: ... bar = 42 ... >>> x = B() >>> y = B() >>> x.bar 42 >>> y.bar 42 If neither is what you want please give a concrete example or a more detailed plain-english description. -- https://mail.python.org/mailman/listinfo/python-list
newbie question re classes and self
Can I pass self(or all its variables) to a class? Basically, how do I make all the variables defined in self in the calling python script available to the python class I want to call? -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes - delegation question.
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes: However, be warned that there are two subtly different models for delegation. Here's the one that people seem to forget: http://code.activestate.com/recipes/519639-true-lieberman-style-delegation-in-python/ Very interesting! The recipe at that URL works only on Python 2. Here is a version which works on both Python 2 and Python 3 URL:https://gitorious.org/lieberman-style-delegation/lieberman-style-delegation/. Licensed under the PSF license, which isn't really appropriate [0] but that's the license under which the original was received. [0] It's only appropriate for Python itself, and contributions to Python shouldn't even be licensed that way URL:https://wiki.python.org/moin/PythonSoftwareFoundationLicenseFaq#What_if_I_want_to_contribute_my_code_to_the_PSF.3F. Apache Software Foundation License 2.0 would be better. -- \ “When I get new information, I change my position. What, sir, | `\ do you do with new information?” —John Maynard Keynes | _o__) | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes - delegation question.
dieter wrote: Ivan Evstegneev webmailgro...@gmail.com writes: I have a question about delegation coding pattern(I'm working with Python 3.4). Unlike Java, Python supports multiple inheritance. This means that you need delegation much more rarely in Python. Python does not have much special support for delegation: usually, you must delegate explicitely - maybe using a delagating decorator. You might *need* delegation more rarely, but some people believe that delegation and composition is a better design pattern than inheritance: http://learnpythonthehardway.org/book/ex44.html http://en.wikipedia.org/wiki/Composition_over_inheritance#Benefits http://joostdevblog.blogspot.com.au/2014/07/why-composition-is-often-better-than.html http://stackoverflow.com/questions/2068158/why-does-cocoa-use-delegates-rather-than-inheritance?lq=1 However, be warned that there are two subtly different models for delegation. Here's the one that people seem to forget: http://code.activestate.com/recipes/519639-true-lieberman-style-delegation-in-python/ -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes - delegation question.
Ivan Evstegneev webmailgro...@gmail.com writes: I have a question about delegation coding pattern(I'm working with Python 3.4). Unlike Java, Python supports multiple inheritance. This means that you need delegation much more rarely in Python. Python does not have much special support for delegation: usually, you must delegate explicitely - maybe using a delagating decorator. ... When code looks like in Case 1, it actually works with standard inheritance model. (with sub and super-class definitions). Also according to the book: *** This code leverages the fact that a class's method can always be called either through an instance (the usual way, where Python sends the instance to the self argument automatically) or through the class (the less common scheme, where you must pass the instance manually). In more symbolic terms, recall that a normal method call of this form: instance.method(args...) is automatically translated by Python into this equivalent form: class.method(instance, args...) *** Furthermore: *** Python provides it automatically only for calls made through an instance. For calls through the class name, you need to send an instance to self yourself; for code inside a method like giveRaise, self already is the subject of the call, and hence the instance to pass along. Calling through the class directly effectively subverts inheritance and kicks the call higher up the class tree to run a specific version. What is considered as a call in this context? Something of the form expression(args...). I.e. any call of a function or method. The discussion above does not directly apply to your situation. It targets more specifically the following case: class Base: ... def f(self, ...): ... class Derived(Base): ... def f(self, ...): ... Base.f(self, ...) ... i.e., you have two classes Base, and Derived where Derived overrides the inherited f and its definition involves the use of the inherited f. Inside the redefinition, you must make explicit that you mean the inherited f and not the f being defined. In those cases, you typically use the pattern Base.f, meaning the f defined in Base. However, you may use the form anywhere - its just rarer in other cases. It you use instance.f, then instance is automatically passed as first argument to f; however, it you use class.f, then nothing is passed on automatically as first parameter. When class.f is finally called, you usually need to pass an instance of class as first parameter explicitely. Is it a code inside class method? Usually, you use class.f inside the redefinition of f in a derived class. But, you can use it anywhere (if you like). For instance(relates to the Case 1): def giveRaise(self, percent, bonus = .10): Person.giveRaise(self, percent + bonus) The call will be : Person.giveRaise(self, percent + bonus) ? Yes. In such a case, when I create an instance: tom = Manager('Tom Jones', 5) and then invoke giveRaise method tom.giveRaise(.10) I essentially say this: class.method(instance, args...) Where class is Person and method is giveRaise and instance is tom? Yes. Moreover, because of how it defined (a method giveRaise), I make a call through the class name? Loosely speaking, yes. What is the call through instance? Your tom.giveRaise. There tom is a Manager instance. Is it this one(according to Case 1): class Person: ... def giveRaise(self, percent): self.pay = int(sel.pay * (1 + percent)) ... and then: bob = Person('Bob Smith', 'dev', 3) bob.giveRaise(.10) Is this call through instance? Yes. ... Questions regard to Case 2 example: class Person: the same... class Manager: def __init__(self, name, pay): self.person = Person(name, 'mgr', pay) --- Initialization of Manager's attribute named 'self.person and embedding a Person object. def giveRaise(self, percent, bonus = .10): -- Defenition of Manager's method named giveRaise and according to the book: self.person.giveRaise(percent + bonus) Intercept and delegate .. My question here is substantially the same: On the one hand we embedding Person into Manager class, On the other hand, when I write this code: tom = Manager('Tom Jones', 5000) I create an instance of Manager that have an attribute named: tom.person, which in turn is a class named Person. ... is an instance of a class ... And when typing: tom.giveRaise(.10) I do kinda same thing. Indeed -- just a bit more convoluted in
RE: Classes - converting external function to class's method.
Again Thanks for your help. I saw that there was a debate about namespace nature. That is what a book says about it(Learning Python 5 Ed. By Mark Lutz): * Classes and Instances Although they are technically two separate object types in the Python model, the classes and instances we put in these trees are almost identical—each type’s main purpose is to serve as another kind of namespace—a package of variables, and a place where we can attach attributes. If classes and instances therefore sound like modules, they should; however, the objects in class trees also have automatically searched links to other namespace objects, and classes correspond to statements, not entire files. Customization via inheritance More generally, classes can build up namespace hierarchies, which define names to be used by objects created from classes in the hierarchy. This supports multiple customizable behaviors more directly than other tools. ...classes live in modules and are namespaces as well, but they add an extra component to attribute lookup called inheritance search. In fact, classes have just three primary distinctions. At a base level, they are mostly just namespaces, much like the modules we studied in Part V. Unlike modules, though, classes also have support for generating multiple objects, for namespace inheritance, and for operator overloading. I'm not pretending to be a smartass here, but as I can understand from the context: Classes are namespaces, but they also have an additional capabilities. BR, Ivan -Original Message- From: Python-list [mailto:python-list- bounces+webmailgroups=gmail@python.org] On Behalf Of Steven D'Aprano Sent: Monday, December 15, 2014 04:01 To: python-list@python.org Subject: Re: Classes - converting external function to class's method. Thomas 'PointedEars' Lahn wrote: Ivan Evstegneev wrote: I have stuck a bit with this example(took this one from the book). Here are a description steps of what I've done till now: Step 1 - creating an empty namespace: class rec: pass IMHO that is not actually creating a namespace; it is just declaring/defining an empty class. And classes are namespaces. As are instances. One clue is the fact that we use exactly the same syntax for accessing names in a namespace regardless of whether the namespace is a package, a module, a class or an instance: import collections.abc # a package namespace math.sin # a module namespace OrderedDict.fromkeys # a class namespace mystring.upper # an instance namespace I call it a clue rather than definitive proof because the syntax is not quite the same for all namespaces. Local and global variables also exist in namespaces, but you don't use dotted notation for them. Another clue is that most of these are implemented by using a __dict__ to store the name:value mapping. Again, that's not universal: instances can optionally use __slots__ instead of __dict__ and packages use the file system. Apart from packages, one can use getattr(), setattr() and delattr() on all of these objects (modules, classes and instances) to manipulate their attributes. Wikipedia says: In general, a namespace is a container for a set of identifiers (also known as symbols, names). https://en.wikipedia.org/wiki/Namespace and that applies to packages, modules, classes, and instances. Last but not least, another clue: in some languages, such as Java, what Python calls attributes are known as *variables*. So per-instance members are called instance variables, per-class members are sometimes called class variables (although not in Java, where I believe they are known as static variables for technical reasons). Personally, I don't like that terminology, but I do recognise that it does reflect a certain connection between names in local/global/instance/class namespaces. BTW, the recommended Python 3.x way is class Rec (object): pass I think you mean Python 2 rather than 3. In Python 2, we have legacy old style or classic classes, and new style classes which inherit from object. In Python 3, classic classes are gone, and inheriting from object is optional. (whereas “pass” is a placeholder statement, a bit like the yada-yada operator of Python) and you should start class identifiers uppercase (therefore, “Rec” instead) in order to avoid name collisions with built-in class identifiers (“str”, “int” etc.) and make it easier to tell apart instantiations from function/method calls. Agreed! It is good practice to name classes with initial capital letter, and instances in all lowercase. If you call that method as the method of a class (object), you need to pass an argument for the first parameter because you have made it positional, not optional
Re: Classes - converting external function to class's method.
Ivan Evstegneev wrote: Hello Everyone, I have stuck a bit with this example(took this one from the book). The example you are working on (adding external functions as methods) is actually a bit more complicated than it seems, as you have discovered. You have this: class rec: pass rec.name = 'Bob' rec.age = 40 x= rec() def uppername(obj): return obj.name.upper() rec.method = uppername This is almost equivalent to the following: class rec: name = 'Bob' age = 40 def method(obj): return obj.name.upper() You then try to use this new method, by calling it from the instance: x.method() -- returns 'BOB' as you expected In this case, it works as you expect. Python looks up method on the instance, and doesn't find anything attached to the instance. It then looks at the class rec, which does have something called method. Because this is a function, Python knows to provide the instance x as the first argument. So the call x.method() ends up turning into this: rec.method(x) Your function uppername() receives x as the argument obj, it looks up obj.name (x.name) and returns it as uppercase. The important part to see here is that when you call a method from an instance: instance.method() Python *automatically* fills in the self argument using the instance. (In your case, you called that argument obj instead of self, but Python doesn't care what it is called.) How does Python know to use x as self? Because it's written right there: x.method uses x as the first argument for method. But this is only done for *instances*, not classes. Now you move on to calling the method from the class itself: rec.method() -- raises TypeError rec.method(rec) -- returns 'BOB' Looking at this, I can guess you are using Python 3, because that won't work in Python 2. Am I right? When you call a method from the class, Python cannot fill in the self argument because it doesn't know what instance to use. This is called an unbound method in Python 2, but in Python 3 it is just a regular function. The important thing here are these two rules: * when you call a method from an instance, Python automatically binds that instance to the first argument (usually called self) of the method: instance.method() -- method gets instance as the self argument * when you call a method from the class, Python cannot bind an instance to self, so you have to do it: Class.method() -- no argument is given! Class.method(instance) -- method gets instance as self In your example, you didn't actually pass an instance, you just passed the class itself: rec.method(rec) But that's okay, because in *this case* the class has a name attribute, so it all works out alright. But normally this would fail. The actual mechanism for how Python does this is called the descriptor protocol, and if you look it up you can find some explanations for it, but be warned that it is quite technical and it is only for very advanced work that you need to care about it. Keeping it in mind, I wrote this code: class myclass: def __init__(self, value): self.name = value def myupper(self): return self.name.upper() And then: b = myclass('bob') b.myupper() 'BOB' I made an assumption that this is what happens(roughly speaking) when I write this: rec.method = uppername Am I right? (close enough maybe?) Close enough. On the other hand, when I checked further: dir(x.method) [, '__self__',...] That is because you are looking the method up on the instance, x. If you look it up on rec, there is no instance so Python cannot give it an __self__ attribute. but dir(rec.method) [ list of method and '__self__' wasn't there.] Exactly! You are looking at a complicated part of Object Oriented Programming, as done by Python, so it is not surprising if it takes a while to understand this. Please feel free to ask more questions if anything is unclear. I got a bit confused. Why actually in instance x x.method() can auto-assign an x to uppername() function argument, but it doesn't work in a class rec itself? When you have an instance x.method then Python knows which instance to use, because it is right there: x. But if you have no instance, only the class: rec.method how does Python know which instance to use? There could be a million instances, or none. Let us look at some strings: the class is called str, and we can have many, many different instances: hello.upper() -- returns HELLO goodbye.upper() -- returns GOODBYE But if I call the method from the class, which instance should it use? str.upper() return HELLO or GOODBYE or 1234 or ABCD or ... The only way is for you to tell Python which instance to use: str.upper(hello) # just like hello.upper() -- returns HELLO So I need to write down an obj argument manually. Why '__self__' exists only in instance x? (maybe because rec, initially was
RE: Classes - converting external function to class's method.
Dear Steven, I very appreciate your answer. You just explained a lot of background things and you did it in more explicit and simple way than it've appeared in the book. I also agree with you about the fact that there are some advanced topics spread within a book's text. It is sometimes hard to a newbie to separate essential and from non essential(I mean more advanced) topics. So I may find myself digging down too much ^_^ In order to assemble the picture I would like to refer to couple of things you mentioned: In this case, it works as you expect. Python looks up method on the instance, and doesn't find anything attached to the instance. It then looks at the class rec, which does have something called method. Because this is a function, Python knows to provide the instance x as the first argument. So the call x.method() ends up turning into this: rec.method(x) I saw something similar to this example, but initially didn't understand what the author meant, so I skipped it Here is a quote from a book(Please see Pic1.jpg too): *** Method Calls If this I2.w reference is a function call, what it really means is call the C3.w function to process I2. That is, Python will automatically map the call I2.w() into the call C3.w(I2), passing in the instance as the first argument to the inherited function. *** This was much confusing, till the moment I've read your explanation on live example. ))) Looking at this, I can guess you are using Python 3, because that won't work in Python 2. Am I right? Yes. I downloaded, Python 3.4 from python.org. Currently working with IDLE. The important part to see here is that when you call a method from an instance: instance.method() Python *automatically* fills in the self argument using the instance. (In your case, you called that argument obj instead of self, but Python doesn't care what it is called.) How does Python know to use x as self? Because it's written right there: x.method uses x as the first argument for method. But this is only done for *instances*, not classes. So, just to summarize all this stuff: A class doesn't have method __self__ by itself. I checked this on some other class provided in the book: class FirstClass: # Define a class object def setdata(self, value):# Define class's methods self.data = value # self is the instance def display(self): print(self.data) And then check it with: dir(FirstClass) [Yep no __self__ here] On the other side, when an instance created, it does have __self__ method. How does a function uppername() looks like, when I apply it to rec class, so it becomes a class's method? I don't understand this question. Well this is an embarrassing moment, it's just shows how lame my English can be ) What I tried to ask here is if there any changes applied by Python to code of function uppername() when it becomes class method (after using this command: rec.method = uppername) Never mind, you already answered it here: This is almost equivalent to the following: class rec: name = 'Bob' age = 40 def method(obj): return obj.name.upper() Moreover, regard to the rec.method = uppername As I can understand, in this case Python does make some changes to the function, but they are implicit. Am I right? Sincerely, Ivan -Original Message- From: Python-list [mailto:python-list- bounces+webmailgroups=gmail@python.org] On Behalf Of Steven D'Aprano Sent: Sunday, December 14, 2014 19:28 To: python-list@python.org Subject: Re: Classes - converting external function to class's method. Ivan Evstegneev wrote: Hello Everyone, I have stuck a bit with this example(took this one from the book). The example you are working on (adding external functions as methods) is actually a bit more complicated than it seems, as you have discovered. You have this: class rec: pass rec.name = 'Bob' rec.age = 40 x= rec() def uppername(obj): return obj.name.upper() rec.method = uppername This is almost equivalent to the following: class rec: name = 'Bob' age = 40 def method(obj): return obj.name.upper() You then try to use this new method, by calling it from the instance: x.method() -- returns 'BOB' as you expected In this case, it works as you expect. Python looks up method on the instance, and doesn't find anything attached to the instance. It then looks at the class rec, which does have something called method. Because this is a function, Python knows to provide the instance x as the first argument. So the call x.method() ends up turning into this: rec.method(x) Your function uppername() receives x as the argument obj, it looks up obj.name (x.name) and returns
Re: Classes - converting external function to class's method.
Ivan Evstegneev wrote: I have stuck a bit with this example(took this one from the book). Here are a description steps of what I've done till now: Step 1 - creating an empty namespace: class rec: pass IMHO that is not actually creating a namespace; it is just declaring/defining an empty class. The equivalent of a namespace in Python is a module; the file path starting from an entry in the PYTHONPATH works like a namespace (the module is considered to be in a package if the directory contains an __init__.py file). (One can assume that this was derived from Java.) BTW, the recommended Python 3.x way is class Rec (object): pass (whereas “pass” is a placeholder statement, a bit like the yada-yada operator of Python) and you should start class identifiers uppercase (therefore, “Rec” instead) in order to avoid name collisions with built-in class identifiers (“str”, “int” etc.) and make it easier to tell apart instantiations from function/method calls. This recommendation applies to other similar OOPLs too, but ISTM is especially important in Python code where there is no “new” keyword used in instantiation. Step 4 - write down external function: def uppername(obj): return obj.name.upper() […] Step 6 - Creating a class method: rec.method = uppername […] x.method() 'BOB' rec.method() . . TypeError: uppername() missing 1 required positional argument: 'obj' and then: rec.method(rec) 'BOB' So my the question is: what is going on here? How this actually works? Short answer: Calling rec.method(x) is equivalent to calling x.method() if type(x) == rec. | class C (object): pass | def foo (self): | ... print(self) | C.foo = foo | C.foo() | Traceback (most recent call last): | File stdin, line 1, in module | TypeError: foo() missing 1 required positional argument: 'self' | o = C() | C.foo(o) | __main__.C object at 0x7f64a7458be0 | o.foo() | __main__.C object at 0x7f64a7458be0 Long answer: If you call that method as the method of a class (object), you need to pass an argument for the first parameter because you have made it positional, not optional (it has no default value). If you pass (a reference to) the class as first argument of that method, the class is the object whose attribute is accessed. Classes are objects (this, too, was probably derived from Java). (In fact, AFAIK almost everything is an object in Python; there are no primitive data types at all.) If instead you call that method as the method of an instance, the first argument is a reference to that instance implicitly, so the signature of the method is met implicitly and there is no error. (See below for an explanation as to why “self.name” still works.) Any arguments that you pass then in the argument list are passed as second, third aso. argument to the method. To this method, then, you MUST NOT pass other arguments because it does not take any more than already supplied implicitly. [Fixed comb-quote; please keep to at most 80 characters per line, best 72] According to the book's downside note: In fact, this is one of the reasons the self argument must always be explicit in Python methods-because methods can be created as simple functions independent of a class, they need to make the implied instance argument explicit. They can be called as either functions or methods, and Python can neither guess nor assume that a simple function might eventually become a class's method. The main reason for the explicit self argument, though, is to make the meanings of names more obvious: names not referenced through self are simple variables mapped to scopes, while names referenced through self with attribute notation are obviously instance attributes. *** Exactly. Keeping it in mind, I wrote this code: class myclass: def __init__(self, value): self.name = value def myupper(self): return self.name.upper() And then: b = myclass('bob') b.myupper() 'BOB' I made an assumption that this is what happens(roughly speaking) when I write this: rec.method = uppername Am I right? (close enough maybe?) Close, maybe. The difference is that in the original code the class has the attribute and the instance merely inherits it, while in the code above only the instance has the attribute. IOW, in the code above the attribute (value) is not implicitly shared with other instances of that class. And ISTM that with the original code it is not possible to modify the attribute value except by accessing it directly or through a method that is passed the reference to the *class* (because a simple assignment in a method merely defines a local variable; there appears to be no closure over class attributes). Compare , | class C (object): | ...
Re: Classes - converting external function to class's method.
On 12/14/2014 6:15 PM, Thomas 'PointedEars' Lahn wrote: Ivan Evstegneev wrote: I have stuck a bit with this example(took this one from the book). Here are a description steps of what I've done till now: Step 1 - creating an empty namespace: class rec: pass IMHO that is not actually creating a namespace; it is just declaring/defining an empty class. I pythonland, a namespace is a many to one mapping between names and objects. They are usually but not necessarily implemented with dicts. Some might restrict the term to a mapping with a .attribute interface for getting and setting. Others consider any string-key dict to be a namespace. The types module has a class SimpleNamespace. It has been proposed to move it to builtins with the name 'namespace'. BTW, the recommended Python 3.x way is class Rec (object): pass I hope you meant Python *2*.x, where '(object)' *is* needed to make a newstyle class. In 3.x, '(object)' is optional and normally omitted except in code meant to run unchanged in 2 and 3. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes - converting external function to class's method.
Terry Reedy wrote: On 12/14/2014 6:15 PM, Thomas 'PointedEars' Lahn wrote: Ivan Evstegneev wrote: I have stuck a bit with this example(took this one from the book). Here are a description steps of what I've done till now: Step 1 - creating an empty namespace: class rec: pass IMHO that is not actually creating a namespace; it is just declaring/defining an empty class. I pythonland, a namespace is a many to one mapping between names and objects. They are usually but not necessarily implemented with dicts. […] BTW, the recommended Python 3.x way is class Rec (object): pass I hope you meant Python *2*.x, I did not. where '(object)' *is* needed to make a newstyle class. In 3.x, '(object)' is optional and normally omitted except in code meant to run unchanged in 2 and 3. Your statements are corroborated by the Language Reference: https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces https://docs.python.org/2.7/reference/datamodel.html#new-style-and-classic-classes Thanks. -- PointedEars -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes - converting external function to class's method.
Thomas 'PointedEars' Lahn wrote: Ivan Evstegneev wrote: I have stuck a bit with this example(took this one from the book). Here are a description steps of what I've done till now: Step 1 - creating an empty namespace: class rec: pass IMHO that is not actually creating a namespace; it is just declaring/defining an empty class. And classes are namespaces. As are instances. One clue is the fact that we use exactly the same syntax for accessing names in a namespace regardless of whether the namespace is a package, a module, a class or an instance: import collections.abc # a package namespace math.sin # a module namespace OrderedDict.fromkeys # a class namespace mystring.upper # an instance namespace I call it a clue rather than definitive proof because the syntax is not quite the same for all namespaces. Local and global variables also exist in namespaces, but you don't use dotted notation for them. Another clue is that most of these are implemented by using a __dict__ to store the name:value mapping. Again, that's not universal: instances can optionally use __slots__ instead of __dict__ and packages use the file system. Apart from packages, one can use getattr(), setattr() and delattr() on all of these objects (modules, classes and instances) to manipulate their attributes. Wikipedia says: In general, a namespace is a container for a set of identifiers (also known as symbols, names). https://en.wikipedia.org/wiki/Namespace and that applies to packages, modules, classes, and instances. Last but not least, another clue: in some languages, such as Java, what Python calls attributes are known as *variables*. So per-instance members are called instance variables, per-class members are sometimes called class variables (although not in Java, where I believe they are known as static variables for technical reasons). Personally, I don't like that terminology, but I do recognise that it does reflect a certain connection between names in local/global/instance/class namespaces. BTW, the recommended Python 3.x way is class Rec (object): pass I think you mean Python 2 rather than 3. In Python 2, we have legacy old style or classic classes, and new style classes which inherit from object. In Python 3, classic classes are gone, and inheriting from object is optional. (whereas “pass” is a placeholder statement, a bit like the yada-yada operator of Python) and you should start class identifiers uppercase (therefore, “Rec” instead) in order to avoid name collisions with built-in class identifiers (“str”, “int” etc.) and make it easier to tell apart instantiations from function/method calls. Agreed! It is good practice to name classes with initial capital letter, and instances in all lowercase. If you call that method as the method of a class (object), you need to pass an argument for the first parameter because you have made it positional, not optional (it has no default value). If you pass (a reference to) the class as first argument of that method, the class is the object whose attribute is accessed. Classes are objects (this, too, was probably derived from Java). (In fact, AFAIK almost everything is an object in Python; there are no primitive data types at all.) You are correct that everything is an object in Python, but wrong that this is derived from Java. As I understand it, Java classes are not values: you cannot assign a class to a variable, or create classes on the fly, or delete them, or stick them in lists, etc. Well, I say that you can't do it, but you actually can, using reflection and other tricks. But the important thing is that you need to use special techniques to work around the fact that classes aren't values and therefore not implemented as objects in Java. What is natural in Python is unnatural in Java. http://stackoverflow.com/questions/2320404/creating-classes-dynamically-with-java [...] If you intend the function to be called as the method of an instance, you would be well-advised to name the parameter “self”, as recommended. (Which is probably derived from Smalltalk-80 and Self, some of the first OOPLs.) Good advice. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
- Original Message - From: Gregory Ewing greg.ew...@canterbury.ac.nz Steven D'Aprano wrote: Like all good Pythonistas[1], we hate Java and think that getter/setter methods are pointless. But come on, they're not *wrong*, What's wrong is the statement that getters and setters are necessary to allow the implementation to change without changing the interface. That's factually incorrect in regard to Python. -- Greg I'm not sure that is what the course was stating: The advantage of following this practice is that the implementer of the class definition (often someone other than the user of the class) may restructure the organization of the data fields associated with the object while avoiding the need to rewrite code that uses the class. I agree with Steven on that one, while getters/setters are not the preferred way, they are not utterly wrong. Python uses the descriptor protocol which is basically getters and setters. It's is just hidden by a strange decorator syntax. JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Nov 2, 2014 5:31 AM, Denis McMahon denismfmcma...@gmail.com wrote: And perhaps that also addresses the square - rectangle (or circle - ellipse) issue - square, rectangle and rhombus are all forms of quadrilateral, and perhaps should all inherit a base class Quadrilateral, rather than trying (and partially failing) to inherit each other. No, it doesn't matter whether you have square inheriting from rectangle, rhombus or quadrilateral. If the base class has mutator methods, you're still going to have this problem when they allow the object to be mutated in ways that violate the restrictions of the subclass. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Tue, Nov 4, 2014 at 12:50 AM, Dennis Lee Bieber wlfr...@ix.netcom.com wrote: On Mon, 3 Nov 2014 03:12:32 + (UTC), Denis McMahon denismfmcma...@gmail.com declaimed the following: So: Quadrilateral Parallelogram Square Rectangle Rhombus Diamond (4 sides eq) Trapezoid Arrowhead Is an arrowhead a trapezoid? I'd probably indent square under rectangle, and indent diamond where it is -- both being restrictions on rectangle/rhombus But we may need another category, convex and concave; the arrowhead would fall into the concave grouping. That's fine if you're creating a taxonomical hierarchy of immutables, but neither works if you're creating a mutable class hierarchy that follows LSP. The only way you can make any of this work (as someone suggested earlier, I believe) is by having __new__ potentially return a subclass, so if you ask Parallelogram to give you one with all sides equal and all angles equal, it gives you back a Square. But since a square is a special form of rhombus as well as a special form of rectangle, you'd have to use multiple inheritance or an AST-style subclass hook to verify. Of course, if you're going down that route, you probably want to take this up a level and have a Shape class, and have the subclass hook simply check if it's four-sided as well. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
Jean-Michel Pichavant wrote: I agree with Steven on that one, while getters/setters are not the preferred way, they are not utterly wrong. I'm not saying that they're wrong in general, only that they're wrong for *Python*. This matters, because the course in question is purportedly teaching Python. To make a blanket statement like that in a Python course, without pointing out that it applies *only* to some languages *other* than Python, is grossly misleading. Now it may be that the quotation is taken out of context, and the instructor did in fact point this out, but the way the paragraph is worded, it sounds like it's just been blindly lifted from some Java or C++ book. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Mon, 03 Nov 2014 06:29:39 +, Dan Sommers wrote: On Mon, 03 Nov 2014 03:12:32 +, Denis McMahon wrote: Quadrilateral Parallelogram Square Rectangle Rhombus Diamond (4 sides eq) Trapezoid Arrowhead What's the difference between a Diamond and a Rhombus? Oops, I was thinking a rhombus was a general parallelogram, my mistake. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
Denis McMahon wrote: On Mon, 03 Nov 2014 06:29:39 +, Dan Sommers wrote: What's the difference between a Diamond and a Rhombus? Oops, I was thinking a rhombus was a general parallelogram, my mistake. Some diamonds are neither rhombuses nor parallelograms: http://minecraft.gamepedia.com/Diamond More a sort of irregular hexagon... -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
Jean-Michel Pichavant wrote: Python uses the descriptor protocol which is basically getters and setters. It's is just hidden by a strange decorator syntax. This is about the interface, not the implementation. Getters and setters in this context means designing the API of your class to have things like getFoo() and setFoo() in it. That's not just totally unnecessary in Python, it's counterproductive. It makes the API tedious to use for no benefit. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Sat, 01 Nov 2014 12:42:10 -0400, Seymore4Head wrote: OK Maybe I misunderstood the question. My answer to you then is ..I don't know. I will have to think about it some more. The question (I thought) was to write a class for Square that inherited a class Rectangle but imposed on it the additional constraints of a square over a rectangle, namely that length == width. To do this, you need to override the inherited methods to set length and width with new methods to set length and width as follows: when setting length, also set width equal to length. when setting width, also set length equal to width. For bonus points, if your constructor accepts width and length parameters (from the Rectangle constructor) then detect if they are different and raise a suitable error. from math import sqrt class SquareGeometryError(Exception): The parameters create an illegal geometry for a square pass class Rectangle: def __init__(self,length,width): self.length=length self.width=width def area(self): return self.length*self.width def perimeter(self): return 2*self.length+2*self.width def diagonal(self): return sqrt(self.length*self.length+self.width*self.width) def get_width(self): return self.width def get_length(self): return self.length def set_width(self, width): self.width = width def set_length(self, length): self.length = length class Square(Rectangle): _def _init__(self, length, width): if not length == width: raise SquareGeometryError(Length must equal width) self.length = length # or width self.width = length # or width def set_width(self, width): self.length = width self.width = width def set_length(self, length): self.length = length self.width = length Note that to make my square, I only need to over-ride those rectangle methods which allow the setting of length and width to enforce squareness upon the square. All the other methods of rectangle will work equally well for the square. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On 2 November 2014 20:50, Denis McMahon denismfmcma...@gmail.com wrote: The question (I thought) was to write a class for Square that inherited a class Rectangle but imposed on it the additional constraints of a square over a rectangle, namely that length == width. I'm late to the party and this has already been partially addressed in the thread, but it always annoys me. A square is as much a rhombus with 90 degree angles as it is a rectangle with equal length and width, and yet I *never* see the former given as an option. If course, that's probably because rectangles have a multitude of uses for user interfaces, whilst other quadrilaterals are somewhat less useful. Tim Delaney -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
Steven D'Aprano wrote: Like all good Pythonistas[1], we hate Java and think that getter/setter methods are pointless. But come on, they're not *wrong*, What's wrong is the statement that getters and setters are necessary to allow the implementation to change without changing the interface. That's factually incorrect in regard to Python. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Sun, 02 Nov 2014 21:32:13 +1100, Tim Delaney wrote: On 2 November 2014 20:50, Denis McMahon denismfmcma...@gmail.com wrote: The question (I thought) was to write a class for Square that inherited a class Rectangle but imposed on it the additional constraints of a square over a rectangle, namely that length == width. I'm late to the party and this has already been partially addressed in the thread, but it always annoys me. A square is as much a rhombus with 90 degree angles as it is a rectangle with equal length and width, and yet I *never* see the former given as an option. If course, that's probably because rectangles have a multitude of uses for user interfaces, whilst other quadrilaterals are somewhat less useful. And perhaps that also addresses the square - rectangle (or circle - ellipse) issue - square, rectangle and rhombus are all forms of quadrilateral, and perhaps should all inherit a base class Quadrilateral, rather than trying (and partially failing) to inherit each other. -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On 11/02/2014 01:50 AM, Denis McMahon wrote: [snip] from math import sqrt class SquareGeometryError(Exception): The parameters create an illegal geometry for a square pass class Rectangle: def __init__(self,length,width): self.length=length self.width=width def area(self): return self.length*self.width def perimeter(self): return 2*self.length+2*self.width def diagonal(self): return sqrt(self.length*self.length+self.width*self.width) def get_width(self): return self.width def get_length(self): return self.length def set_width(self, width): self.width = width def set_length(self, length): self.length = length class Square(Rectangle): _def _init__(self, length, width): if not length == width: raise SquareGeometryError(Length must equal width) self.length = length # or width self.width = length # or width def set_width(self, width): self.length = width self.width = width def set_length(self, length): self.length = length self.width = length Note that to make my square, I only need to over-ride those rectangle methods which allow the setting of length and width to enforce squareness upon the square. All the other methods of rectangle will work equally well for the square. Why do you want to instantiate a Square with two parameters? You only need one -- side. I agree that since you are inheriting from Rectangle you need to keep the length and width attributes to allow the get/set of length/width, so you do need to override the Rectangle set methods. Consider this version: # -- code - class Square(Rectangle): def __init__(self, side): self.set_side(side) def get_side(self): return self.length # or width def set_side(self, side): self.length = self.width = side def set_width(self, width): self.set_side(width) def set_length(self, length): self.set_side(length) # -- /code This also eliminates the need for your exception. Of course, it still allows someone to directly change either the length or width -- but since we are all consenting adults here, anyone who does this should know the consequences. ;-) -=- Larry -=- -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Sun, 02 Nov 2014 11:31:12 -0500, Dennis Lee Bieber wrote: On Sun, 2 Nov 2014 12:27:06 + (UTC), Denis McMahon denismfmcma...@gmail.com declaimed the following: On Sun, 02 Nov 2014 21:32:13 +1100, Tim Delaney wrote: If course, that's probably because rectangles have a multitude of uses for user interfaces, whilst other quadrilaterals are somewhat less useful. And perhaps that also addresses the square - rectangle (or circle - ellipse) issue - square, rectangle and rhombus are all forms of quadrilateral, and perhaps should all inherit a base class Quadrilateral, rather than trying (and partially failing) to inherit each other. I'd class them as parallelograms -- as they differ from a trapezoid in that opposite faces are parallel... Not to mention arrow heads where two adjacent sides actually bend inwards. So: Quadrilateral Parallelogram Square Rectangle Rhombus Diamond (4 sides eq) Trapezoid Arrowhead Is an arrowhead a trapezoid? -- Denis McMahon, denismfmcma...@gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Mon, 03 Nov 2014 03:12:32 +, Denis McMahon wrote: Quadrilateral Parallelogram Square Rectangle Rhombus Diamond (4 sides eq) Trapezoid Arrowhead What's the difference between a Diamond and a Rhombus? Is an arrowhead a trapezoid? No. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Fri, Oct 31, 2014 at 7:06 PM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: And there are times when using getters and setters is the right choice. Properties should only be used for quite lightweight calculations, because attribute access is supposed to be fast. If your calculation is complex, time-consuming or might fail, using a property is a bad idea and you should use an explicit getter method, possibly with a setter if needed. I agree except that in this scenario you should probably use a verb other than get, since getters should also be fast. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Sat, Nov 1, 2014 at 5:12 PM, Ian Kelly ian.g.ke...@gmail.com wrote: On Fri, Oct 31, 2014 at 7:06 PM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: And there are times when using getters and setters is the right choice. Properties should only be used for quite lightweight calculations, because attribute access is supposed to be fast. If your calculation is complex, time-consuming or might fail, using a property is a bad idea and you should use an explicit getter method, possibly with a setter if needed. I agree except that in this scenario you should probably use a verb other than get, since getters should also be fast. Maybe. get_track_length() might be a reasonable method name for something that opens an audio file, reads its header, and returns its length in seconds. It should be a method rather than a property (attribute access should be fast), but get makes sense here, as it's not calculating or anything, it's just retrieving information. But yes, if it's a calculation, calc would be more common. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Sat, 01 Nov 2014 12:00:46 -0400, Dennis Lee Bieber wlfr...@ix.netcom.com wrote: On Fri, 31 Oct 2014 19:32:13 -0400, Seymore4Head Seymore4Head@Hotmail.invalid declaimed the following: class Rectangle(object): def __init__(self, length, width=None): self.length = length if width is None: self.width = length else: self.width = width def area(self): return self.length * self.width def perimeter(self): return 2 * (self.length + self.width) class Square(Rectangle): def area(self): return self.length * self.width def perimeter(self): return 2 * (self.length + self.width) Why did you redefine area and perimeter? Those are supposed to be inherited operations from Rectangle. You've duplicated what should not have been changed, and removed everything that makes a Square a Square. The assignment was to create a Square class that enforces the property of squareness (length = width, or a simple side). What you created does not do that. a=Rectangle(3,5) print (a.area()) print (a.perimeter()) b=Rectangle(5,7) print (b.area()) print (b.perimeter()) c=Square(4) print (c.area()) print (c.perimeter()) You're tests ignore the case of /changing/ side/length/width... Consider what happens if you execute c.length = 5 c.width = 9 OK Maybe I misunderstood the question. My answer to you then is ..I don't know. I will have to think about it some more. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
Seymore4Head Seymore4Head@Hotmail.invalid a écrit dans le message de news:51755at03r0bidjqh3qf0hhpvjr8756...@4ax.com... class pet: def set_age(self,age): self.age=age def get_age(self): return self.age pax=pet pax.set_age(4) Traceback (most recent call last): File C:\Functions\test.py, line 18, in module pax.set_age(4) TypeError: set_age() missing 1 required positional argument: 'age' I am trying to pass 4 as the age. Obviously I am doing it wrong. Hi I am a beginner too, but I find it strange that your pet class has no __init__ method to construct instances -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
ast nom...@invalid.com a écrit dans le message de news:545350c3$0$23449$426a7...@news.free.fr... I am a beginner too, but I find it strange that your pet class has no __init__ method to construct instances It works anyway because __init__ is taken in the parent Class, probably Object. But this means that a method can create a new attribute not previously created with __init__. Is that correct ? -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Fri, Oct 31, 2014 at 8:18 PM, ast nom...@invalid.com wrote: But this means that a method can create a new attribute not previously created with __init__. Is that correct ? That's always the case. There's nothing special about __init__ for creating attributes. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Thu, 30 Oct 2014 17:34:57 -0400, Seymore4Head wrote: On Thu, 30 Oct 2014 14:28:19 -0700, Larry Hudson org...@yahoo.com wrote: On 10/30/2014 01:16 PM, Seymore4Head wrote: class pet: def set_age(self,age): self.age=age def get_age(self): return self.age pax=pet pax.set_age(4) Traceback (most recent call last): File C:\Functions\test.py, line 18, in module pax.set_age(4) TypeError: set_age() missing 1 required positional argument: 'age' I am trying to pass 4 as the age. Obviously I am doing it wrong. You have already received the answer -- pax=pet should be pax=pet(), but I have a simple side-comment about style. It is common Python convention to capitalize class names, IOW make this class Pet instead of class pet. This is convention not a requirement, but it does help distinguish class names from ordinary variable names -- especially to others reading your code (as well as yourself a few days later). ;-) -=- Larry -=- I try to take typing shortcuts and it bites me in the behind. Good suggestion Thanks If shortcuts were safe and easy they would not be shortcuts they would be the way. It is best to avoid shortcuts whilst learning untill you know the full implications. you will find your learning goes much smother faster. -- We are all in the gutter, but some of us are looking at the stars. -- Oscar Wilde -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Fri, 31 Oct 2014 10:05:03 +0100, ast nom...@invalid.com wrote: Seymore4Head Seymore4Head@Hotmail.invalid a écrit dans le message de news:51755at03r0bidjqh3qf0hhpvjr8756...@4ax.com... class pet: def set_age(self,age): self.age=age def get_age(self): return self.age pax=pet pax.set_age(4) Traceback (most recent call last): File C:\Functions\test.py, line 18, in module pax.set_age(4) TypeError: set_age() missing 1 required positional argument: 'age' I am trying to pass 4 as the age. Obviously I am doing it wrong. Hi I am a beginner too, but I find it strange that your pet class has no __init__ method to construct instances Because the topic of that lesson was getter setter. I can construct an __init___ but I was practicing get/set. This stuff is coming to me slowly. I need to rinse and repeat quite a few more times, before I follow what is going on. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On 31/10/2014 09:05, ast wrote: Seymore4Head Seymore4Head@Hotmail.invalid a écrit dans le message de news:51755at03r0bidjqh3qf0hhpvjr8756...@4ax.com... class pet: def set_age(self,age): self.age=age def get_age(self): return self.age pax=pet pax.set_age(4) Traceback (most recent call last): File C:\Functions\test.py, line 18, in module pax.set_age(4) TypeError: set_age() missing 1 required positional argument: 'age' I am trying to pass 4 as the age. Obviously I am doing it wrong. Hi I am a beginner too, but I find it strange that your pet class has no __init__ method to construct instances __init__ initialises instances, __new__ constructs them -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Fri, 31 Oct 2014 09:59:30 GMT, alister alister.nospam.w...@ntlworld.com wrote: On Thu, 30 Oct 2014 17:34:57 -0400, Seymore4Head wrote: On Thu, 30 Oct 2014 14:28:19 -0700, Larry Hudson org...@yahoo.com wrote: On 10/30/2014 01:16 PM, Seymore4Head wrote: class pet: def set_age(self,age): self.age=age def get_age(self): return self.age pax=pet pax.set_age(4) Traceback (most recent call last): File C:\Functions\test.py, line 18, in module pax.set_age(4) TypeError: set_age() missing 1 required positional argument: 'age' I am trying to pass 4 as the age. Obviously I am doing it wrong. You have already received the answer -- pax=pet should be pax=pet(), but I have a simple side-comment about style. It is common Python convention to capitalize class names, IOW make this class Pet instead of class pet. This is convention not a requirement, but it does help distinguish class names from ordinary variable names -- especially to others reading your code (as well as yourself a few days later). ;-) -=- Larry -=- I try to take typing shortcuts and it bites me in the behind. Good suggestion Thanks If shortcuts were safe and easy they would not be shortcuts they would be the way. It is best to avoid shortcuts whilst learning untill you know the full implications. you will find your learning goes much smother faster. Good advice. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Fri, Oct 31, 2014 at 8:05 AM, Seymore4Head Seymore4Head@hotmail.invalid wrote: Because the topic of that lesson was getter setter. I can construct an __init___ but I was practicing get/set. Doesn't sound like a very good lesson to me. Getters and setters are the Java way of doing things. The Pythonic way is to just use an attribute, and then replace it with a property in the unlikely event that getter/setter logic needs to be added. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On 2014-10-31, Ian Kelly ian.g.ke...@gmail.com wrote: On Fri, Oct 31, 2014 at 8:05 AM, Seymore4Head Seymore4Head@hotmail.invalid wrote: Because the topic of that lesson was getter setter. I can construct an __init___ but I was practicing get/set. Doesn't sound like a very good lesson to me. It's not. It's teaching java or C++ or some other language while using a Python compiler. Getters and setters are the Java way of doing things. The Pythonic way is to just use an attribute, and then replace it with a property in the unlikely event that getter/setter logic needs to be added. Exactly. -- Grant Edwards grant.b.edwardsYow! I have the power to at HALT PRODUCTION on all gmail.comTEENAGE SEX COMEDIES!! -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Fri, 31 Oct 2014 15:49:43 + (UTC), Grant Edwards invalid@invalid.invalid wrote: On 2014-10-31, Ian Kelly ian.g.ke...@gmail.com wrote: On Fri, Oct 31, 2014 at 8:05 AM, Seymore4Head Seymore4Head@hotmail.invalid wrote: Because the topic of that lesson was getter setter. I can construct an __init___ but I was practicing get/set. Doesn't sound like a very good lesson to me. It's not. It's teaching java or C++ or some other language while using a Python compiler. Getters and setters are the Java way of doing things. The Pythonic way is to just use an attribute, and then replace it with a property in the unlikely event that getter/setter logic needs to be added. Exactly. In this class, we will follow the practice of accessing the contents of objects using methods known as getters and setters. While not required by Python, this practice encourages the user of the class to manipulates class objects solely via class methods. The advantage of following this practice is that the implementer of the class definition (often someone other than the user of the class) may restructure the organization of the data fields associated with the object while avoiding the need to rewrite code that uses the class. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Sat, Nov 1, 2014 at 3:31 AM, Seymore4Head Seymore4Head@hotmail.invalid wrote: [presumably quoting his course material] In this class, we will follow the practice of accessing the contents of objects using methods known as getters and setters. While not required by Python, this practice encourages the user of the class to manipulates class objects solely via class methods. The advantage of following this practice is that the implementer of the class definition (often someone other than the user of the class) may restructure the organization of the data fields associated with the object while avoiding the need to rewrite code that uses the class. Yep, that's teaching C++/Java coding using Python. Isn't it time you got onto a better course? Time and time again you've been going down inadvisable paths, and it seems to me you could do better with the inbuilt tutorial rather than this kind of course. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Sat, 1 Nov 2014 03:37:29 +1100, Chris Angelico ros...@gmail.com wrote: On Sat, Nov 1, 2014 at 3:31 AM, Seymore4Head Seymore4Head@hotmail.invalid wrote: [presumably quoting his course material] In this class, we will follow the practice of accessing the contents of objects using methods known as getters and setters. While not required by Python, this practice encourages the user of the class to manipulates class objects solely via class methods. The advantage of following this practice is that the implementer of the class definition (often someone other than the user of the class) may restructure the organization of the data fields associated with the object while avoiding the need to rewrite code that uses the class. Yep, that's teaching C++/Java coding using Python. Isn't it time you got onto a better course? Time and time again you've been going down inadvisable paths, and it seems to me you could do better with the inbuilt tutorial rather than this kind of course. ChrisA inbuilt tutorial? The course is free. You can't beat the price. It is only for a few more weeks. Trying to learn from reading the Internet has no set direction. I need a little nudge. More like a shove. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Fri, 31 Oct 2014 10:05:03 +0100, ast nom...@invalid.com wrote: Seymore4Head Seymore4Head@Hotmail.invalid a écrit dans le message de news:51755at03r0bidjqh3qf0hhpvjr8756...@4ax.com... class pet: def set_age(self,age): self.age=age def get_age(self): return self.age pax=pet pax.set_age(4) Traceback (most recent call last): File C:\Functions\test.py, line 18, in module pax.set_age(4) TypeError: set_age() missing 1 required positional argument: 'age' I am trying to pass 4 as the age. Obviously I am doing it wrong. Hi I am a beginner too, but I find it strange that your pet class has no __init__ method to construct instances What material have you used to take you up to classes? -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Sat, Nov 1, 2014 at 3:47 AM, Seymore4Head Seymore4Head@hotmail.invalid wrote: inbuilt tutorial? The course is free. You can't beat the price. It is only for a few more weeks. Trying to learn from reading the Internet has no set direction. I need a little nudge. More like a shove. https://docs.python.org/3/tutorial/ Same price. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
Seymore4Head wrote: Because the topic of that lesson was getter setter. I can construct an __init___ but I was practicing get/set. What lesson is that? Using getters/setters is discouraged in Python. This stuff is coming to me slowly. I need to rinse and repeat quite a few more times, before I follow what is going on. Start with the simplest class possible: class MyClass: pass Right now, that class has a name, MyClass, no methods, and no data. But we can still create an instance. Call the class, as if it were a function, to create the instance: obj = MyClass() What's the relationship between instances and classes? Classes are a general type of entity, instances are a specific example of that entity. You can have many instances from a class. So: Class: Dog Instances: Rin-Tin-Tin, Lassie, Hooch (from the Turner and Hooch movie), Marmaduke, Gaspode the Wonder Dog, Spike the Bulldog, etc. Class: Wizard Instances: Gandalf, Dumbledore, the Wizard of Oz, Rincewind, etc. Class: int Instances: 0, 1, 2, -5, 23, 19874023, etc. You can confirm that obj is now an instance of MyClass: print(isinstance(obj, MyClass)) will print True. What can you do with obj? It has no interesting methods, and no data. But we can give it some! Python, unlike some languages, allows you to dynamically add data attributes to instances on the fly, without pre-defining them. obj.value = 23.0 obj.message = hello world! print(obj.value) print(obj.message) will associate the data 23.0 and hello world to the attributes value and message of the instance obj. Let's make the class a bit easier to use, at the expense of doing a bit more work up front: class MyClass: def __init__(self, value, message): self.value = value self.message = message obj = MyClass(23.0, hello world) print(obj.value) print(obj.message) The __init__ method is automatically called when you call the class as if it were a function. Because the __init__ method has two arguments (plus the special self argument), you have to call the class with two arguments. They get used as the value and message respectively. Or we can give it getters and setters: class MyClass: def set_value(self, value): self.value = value def get_value(self): return self.value def set_message(self, message): self.message = message def get_message(self): return self.message obj = MyClass() obj.set_value(23.0) obj.set_message(hello world) print(obj.get_value()) print(obj.get_message()) If you're thinking that's a lot of extra work for not much benefit, 99.99% of the time you're right. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On 10/31/2014 12:31 PM, Seymore4Head wrote: In this class, we will follow the practice of accessing the contents of objects using methods known as getters and setters. While not required by Python, this practice encourages the user of the class to manipulates class objects solely via class methods. The advantage of following this practice is that the implementer of the class definition (often someone other than the user of the class) may restructure the organization of the data fields associated with the object while avoiding the need to rewrite code that uses the class. Written by somebody who doesn't understand a fundamental point about Python. It's just not true that the user would have to rewrite code if the implementer change the members. The Python way of writing getters and setters (if/when you get to that stage of a Python class) is through the property decorator or its equivalent. class Pet(): def __init__(self, ): self.internal details set here @property() def age(self): return some_complicated_expression And the user of the class fetches this by using mypet = Pet() hisage = mypet.age No stupid parentheses needed. When the class is first written, no work is needed. When it's updated to multiply the internal age by 7, just write the function, and decorate it to look like a regular attribute. More complicated things can be done. But the point is that the user should just get the age, by accessing the age attribute, and if the implementation needs to change, it can change. The time to make a class complicated, is when it needs to be. And the user should not have to pay the price for just in case. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Sat, 01 Nov 2014 04:06:44 +1100, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: Seymore4Head wrote: Because the topic of that lesson was getter setter. I can construct an __init___ but I was practicing get/set. What lesson is that? Using getters/setters is discouraged in Python. This stuff is coming to me slowly. I need to rinse and repeat quite a few more times, before I follow what is going on. Start with the simplest class possible: class MyClass: pass Right now, that class has a name, MyClass, no methods, and no data. But we can still create an instance. Call the class, as if it were a function, to create the instance: obj = MyClass() What's the relationship between instances and classes? Classes are a general type of entity, instances are a specific example of that entity. You can have many instances from a class. So: Class: Dog Instances: Rin-Tin-Tin, Lassie, Hooch (from the Turner and Hooch movie), Marmaduke, Gaspode the Wonder Dog, Spike the Bulldog, etc. Class: Wizard Instances: Gandalf, Dumbledore, the Wizard of Oz, Rincewind, etc. Class: int Instances: 0, 1, 2, -5, 23, 19874023, etc. You can confirm that obj is now an instance of MyClass: print(isinstance(obj, MyClass)) will print True. What can you do with obj? It has no interesting methods, and no data. But we can give it some! Python, unlike some languages, allows you to dynamically add data attributes to instances on the fly, without pre-defining them. obj.value = 23.0 obj.message = hello world! print(obj.value) print(obj.message) will associate the data 23.0 and hello world to the attributes value and message of the instance obj. Let's make the class a bit easier to use, at the expense of doing a bit more work up front: class MyClass: def __init__(self, value, message): self.value = value self.message = message obj = MyClass(23.0, hello world) print(obj.value) print(obj.message) The __init__ method is automatically called when you call the class as if it were a function. Because the __init__ method has two arguments (plus the special self argument), you have to call the class with two arguments. They get used as the value and message respectively. Or we can give it getters and setters: class MyClass: def set_value(self, value): self.value = value def get_value(self): return self.value def set_message(self, message): self.message = message def get_message(self): return self.message obj = MyClass() obj.set_value(23.0) obj.set_message(hello world) print(obj.get_value()) print(obj.get_message()) If you're thinking that's a lot of extra work for not much benefit, 99.99% of the time you're right. I agree it is more work. But more work means more practice. I need more practice figuring out how these commands work. obj = MyClass() obj.set_value(23.0) obj.set_message(hello world) print(obj.get_value()) print(obj.get_message()) I don't know here to get more (simple) practice problems. I am trying to invent my own. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Sat, 1 Nov 2014 04:02:33 +1100, Chris Angelico ros...@gmail.com wrote: On Sat, Nov 1, 2014 at 3:47 AM, Seymore4Head Seymore4Head@hotmail.invalid wrote: inbuilt tutorial? The course is free. You can't beat the price. It is only for a few more weeks. Trying to learn from reading the Internet has no set direction. I need a little nudge. More like a shove. https://docs.python.org/3/tutorial/ Same price. I run across this page frequently. To me, this is examples. While examples can be quite useful, I don't call this a tutorial. I have found the answer to my question by searching this page several times, but the biggest problem with this page is that you can't copy and paste the examples into IDLE. JMO -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
Seymore4Head Seymore4Head@Hotmail.invalid: In this class, we will follow the practice of accessing the contents of objects using methods known as getters and setters. The biggest problem in this OO disease is that it makes you think of objects as data containers instead of dynamic agents. An object is defined through its behavior, not what the black box contains. Marko -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Fri, Oct 31, 2014 at 12:31 PM, Seymore4Head Seymore4Head@hotmail.invalid wrote: I run across this page frequently. To me, this is examples. While examples can be quite useful, I don't call this a tutorial. I have found the answer to my question by searching this page several times, but the biggest problem with this page is that you can't copy and paste the examples into IDLE. Sure you can, just click the little '' button in the upper right of the example box. -- Zach -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Fri, 31 Oct 2014 13:31:44 -0400 Seymore4Head Seymore4Head@Hotmail.invalid wrote: On Sat, 1 Nov 2014 04:02:33 +1100, Chris Angelico ros...@gmail.com wrote: On Sat, Nov 1, 2014 at 3:47 AM, Seymore4Head Seymore4Head@hotmail.invalid wrote: inbuilt tutorial? The course is free. You can't beat the price. It is only for a few more weeks. Trying to learn from reading the Internet has no set direction. I need a little nudge. More like a shove. https://docs.python.org/3/tutorial/ Same price. I run across this page frequently. To me, this is examples. While examples can be quite useful, I don't call this a tutorial. I have found the answer to my question by searching this page several times, but the biggest problem with this page is that you can't copy and paste the examples into IDLE. JMO No, but you can retype them. Copying and pasting teaches nothing. Figuring out how to hunt down the syntax errors your retyping has induced teaches much. -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On 2014-10-31, Seymore4Head Seymore4Head@Hotmail.invalid wrote: On Fri, 31 Oct 2014 15:49:43 + (UTC), Grant Edwards invalid@invalid.invalid wrote: On 2014-10-31, Ian Kelly ian.g.ke...@gmail.com wrote: On Fri, Oct 31, 2014 at 8:05 AM, Seymore4Head Seymore4Head@hotmail.invalid wrote: Because the topic of that lesson was getter setter. I can construct an __init___ but I was practicing get/set. Doesn't sound like a very good lesson to me. It's not. It's teaching java or C++ or some other language while using a Python compiler. Getters and setters are the Java way of doing things. The Pythonic way is to just use an attribute, and then replace it with a property in the unlikely event that getter/setter logic needs to be added. Exactly. In this class, we will follow the practice of accessing the contents of objects using methods known as getters and setters. IOW... In this class, we're not going to learn Python. We're going to learn Java. But actually _using_ Java is too much hassle, so we'll write Java using Python instead. While not required by Python, this practice encourages the user of the class to manipulates class objects solely via class methods. Which is a Java/C++ thing. The advantage of following this practice is that the implementer of the class definition (often someone other than the user of the class) may restructure the organization of the data fields associated with the object while avoiding the need to rewrite code that uses the class. That's wrong. That statement about using getter/setter having that advantage is false (if you're talking about Python). It may be true in Java or C++ or whatever language the lesson's author is teaching, but it's not true of Python. -- Grant Edwards grant.b.edwardsYow! A shapely CATHOLIC at SCHOOLGIRL is FIDGETING gmail.cominside my costume.. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On 2014-10-31, Seymore4Head Seymore4Head@Hotmail.invalid wrote: On Sat, 01 Nov 2014 04:06:44 +1100, Steven D'Aprano Let's make the class a bit easier to use, at the expense of doing a bit more work up front: class MyClass: def __init__(self, value, message): self.value = value self.message = message obj = MyClass(23.0, hello world) print(obj.value) print(obj.message) The __init__ method is automatically called when you call the class as if it were a function. Because the __init__ method has two arguments (plus the special self argument), you have to call the class with two arguments. They get used as the value and message respectively. Or we can give it getters and setters: class MyClass: def set_value(self, value): self.value = value def get_value(self): return self.value def set_message(self, message): self.message = message def get_message(self): return self.message obj = MyClass() obj.set_value(23.0) obj.set_message(hello world) print(obj.get_value()) print(obj.get_message()) If you're thinking that's a lot of extra work for not much benefit, 99.99% of the time you're right. I agree it is more work. But more work means more practice. I need more practice figuring out how these commands work. Except you're practicing doing things the wrong way. If you want to learn Java, then use Java. If you want to learn Python, then don't write Java. -- Grant Edwards grant.b.edwardsYow! HOORAY, Ronald!! at Now YOU can marry LINDA gmail.comRONSTADT too!! -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Fri, 31 Oct 2014 13:18:00 -0400 Seymore4Head Seymore4Head@Hotmail.invalid wrote: On Sat, 01 Nov 2014 04:06:44 +1100, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: Seymore4Head wrote: Because the topic of that lesson was getter setter. I can construct an __init___ but I was practicing get/set. What lesson is that? Using getters/setters is discouraged in Python. This stuff is coming to me slowly. I need to rinse and repeat quite a few more times, before I follow what is going on. Start with the simplest class possible: class MyClass: pass Right now, that class has a name, MyClass, no methods, and no data. But we can still create an instance. Call the class, as if it were a function, to create the instance: obj = MyClass() What's the relationship between instances and classes? Classes are a general type of entity, instances are a specific example of that entity. You can have many instances from a class. So: Class: Dog Instances: Rin-Tin-Tin, Lassie, Hooch (from the Turner and Hooch movie), Marmaduke, Gaspode the Wonder Dog, Spike the Bulldog, etc. Class: Wizard Instances: Gandalf, Dumbledore, the Wizard of Oz, Rincewind, etc. Class: int Instances: 0, 1, 2, -5, 23, 19874023, etc. You can confirm that obj is now an instance of MyClass: print(isinstance(obj, MyClass)) will print True. What can you do with obj? It has no interesting methods, and no data. But we can give it some! Python, unlike some languages, allows you to dynamically add data attributes to instances on the fly, without pre-defining them. obj.value = 23.0 obj.message = hello world! print(obj.value) print(obj.message) will associate the data 23.0 and hello world to the attributes value and message of the instance obj. Let's make the class a bit easier to use, at the expense of doing a bit more work up front: class MyClass: def __init__(self, value, message): self.value = value self.message = message obj = MyClass(23.0, hello world) print(obj.value) print(obj.message) The __init__ method is automatically called when you call the class as if it were a function. Because the __init__ method has two arguments (plus the special self argument), you have to call the class with two arguments. They get used as the value and message respectively. Or we can give it getters and setters: class MyClass: def set_value(self, value): self.value = value def get_value(self): return self.value def set_message(self, message): self.message = message def get_message(self): return self.message obj = MyClass() obj.set_value(23.0) obj.set_message(hello world) print(obj.get_value()) print(obj.get_message()) If you're thinking that's a lot of extra work for not much benefit, 99.99% of the time you're right. I agree it is more work. But more work means more practice. I need more practice figuring out how these commands work. obj = MyClass() obj.set_value(23.0) obj.set_message(hello world) print(obj.get_value()) print(obj.get_message()) I don't know here to get more (simple) practice problems. I am trying to invent my own. Fine. Practice problem that is actually Pythonic. Define a Rectangle class. Give it length and width attributes, no unnecessary getters or setters. Give it perimeter() and area() methods. Define a Square class, subclassed from Rectangle. Use getters/setters to enforce that the length and width must be equal. Confirm that length and width remain locked, and that perimeter() and area() work correctly. -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Fri, 31 Oct 2014 12:39:34 -0500, Zachary Ware zachary.ware+pyl...@gmail.com wrote: On Fri, Oct 31, 2014 at 12:31 PM, Seymore4Head Seymore4Head@hotmail.invalid wrote: I run across this page frequently. To me, this is examples. While examples can be quite useful, I don't call this a tutorial. I have found the answer to my question by searching this page several times, but the biggest problem with this page is that you can't copy and paste the examples into IDLE. Sure you can, just click the little '' button in the upper right of the example box. Ah..so you can. Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Fri, 31 Oct 2014 10:43:19 -0700, Rob Gaddi rgaddi@technologyhighland.invalid wrote: Define a Square class, subclassed from Rectangle. Use getters/setters to enforce that the length and width must be equal. Confirm that length and width remain locked, and that perimeter() and area() work correctly. class Rectangle: def __init__(self,length,width): self.length=length self.width=width def area(self): return self.length*self.width def perimeter(self): return 2*self.length+2*self.width class Square(Rectangle): def set_side (self): if self.length!=self.width: a=Rectangle(3,5) print (a.area()) print (a.perimeter()) b=Rectangle(5,7) print (b.area()) print (b.perimeter()) c=Rectangle(4,4) print (c.area()) print (c.perimeter()) I bombed on the rest. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
Seymore4Head Seymore4Head@Hotmail.invalid a écrit dans le message de news:rbf75ah9l1jp9e72gqr0ncu7bau8cnt...@4ax.com... What material have you used to take you up to classes? It's a french classroom on the web http://openclassrooms.com/courses/apprenez-a-programmer-en-python -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Fri, 31 Oct 2014 19:31:01 +0100, ast nom...@invalid.com wrote: Seymore4Head Seymore4Head@Hotmail.invalid a écrit dans le message de news:rbf75ah9l1jp9e72gqr0ncu7bau8cnt...@4ax.com... What material have you used to take you up to classes? It's a french classroom on the web http://openclassrooms.com/courses/apprenez-a-programmer-en-python I am going to try to learn Python before I learn French, so I won't be going there. :) Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Fri, Oct 31, 2014 at 2:31 PM, ast nom...@invalid.com wrote: Seymore4Head Seymore4Head@Hotmail.invalid a écrit dans le message de news:rbf75ah9l1jp9e72gqr0ncu7bau8cnt...@4ax.com... What material have you used to take you up to classes? It's a french classroom on the web http://openclassrooms.com/courses/apprenez-a-programmer-en-python -- https://mail.python.org/mailman/listinfo/python-list My suggestion for a free tutorial is Learn Python the Hard Way. You won't learn by cutting and pasting. You have to type it in yourself. It will make you learn more because every typo you make will lead you to a new discovery -- Joel Goldstick http://joelgoldstick.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Fri, 31 Oct 2014 14:18:44 -0400, Seymore4Head Seymore4Head@Hotmail.invalid wrote: On Fri, 31 Oct 2014 10:43:19 -0700, Rob Gaddi rgaddi@technologyhighland.invalid wrote: Define a Square class, subclassed from Rectangle. Use getters/setters to enforce that the length and width must be equal. Confirm that length and width remain locked, and that perimeter() and area() work correctly. class Rectangle: def __init__(self,length,width): self.length=length self.width=width def area(self): return self.length*self.width def perimeter(self): return 2*self.length+2*self.width class Square(Rectangle): def set_side (self): if self.length!=self.width: a=Rectangle(3,5) print (a.area()) print (a.perimeter()) b=Rectangle(5,7) print (b.area()) print (b.perimeter()) c=Rectangle(4,4) print (c.area()) print (c.perimeter()) I bombed on the rest. class Rectangle: def __init__(self,length=0,width=0): self.length=length self.width=width def area(self): return self.length*self.width def perimeter(self): return 2*self.length+2*self.width class Square(Rectangle): def set_side (self,side): self.side=side return side*side a=Rectangle(3,5) print (a.area()) print (a.perimeter()) b=Rectangle(5,7) print (b.area()) print (b.perimeter()) c=Rectangle(4,4) print (c.area()) print (c.perimeter()) A little closer. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Fri, 31 Oct 2014 14:41:08 -0400, Joel Goldstick joel.goldst...@gmail.com wrote: On Fri, Oct 31, 2014 at 2:31 PM, ast nom...@invalid.com wrote: Seymore4Head Seymore4Head@Hotmail.invalid a écrit dans le message de news:rbf75ah9l1jp9e72gqr0ncu7bau8cnt...@4ax.com... What material have you used to take you up to classes? It's a french classroom on the web http://openclassrooms.com/courses/apprenez-a-programmer-en-python -- https://mail.python.org/mailman/listinfo/python-list My suggestion for a free tutorial is Learn Python the Hard Way. You won't learn by cutting and pasting. You have to type it in yourself. It will make you learn more because every typo you make will lead you to a new discovery I have watched a few of those videos. And I do have the PDF. I will give it a closer look. Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Sat, Nov 1, 2014 at 4:43 AM, Rob Gaddi rgaddi@technologyhighland.invalid wrote: Define a Square class, subclassed from Rectangle. Use getters/setters to enforce that the length and width must be equal. Confirm that length and width remain locked, and that perimeter() and area() work correctly. Here we go again... http://en.wikipedia.org/wiki/Circle-ellipse_problem Square and Rectangle are just as obviously the other way around in the hierarchy, and it's wrong whichever way you do it. Not a good example. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Friday, October 31, 2014 1:51:23 PM UTC-7, Chris Angelico wrote: On Sat, Nov 1, 2014 at 4:43 AM, Rob Gaddi rgaddi@technologyhighland.invalid wrote: Define a Square class, subclassed from Rectangle. Use getters/setters to enforce that the length and width must be equal. Confirm that length and width remain locked, and that perimeter() and area() work correctly. Here we go again... http://en.wikipedia.org/wiki/Circle-ellipse_problem Square and Rectangle are just as obviously the other way around in the hierarchy, and it's wrong whichever way you do it. Not a good example. ChrisA I've never heard of the Circle-Ellipse problem, and my first instinct to Rob's post was to ask, why would you want to sub-class Rectangle into a Square class? A square is just a special case of a Rectangle. Attempting that kind of sub-classing would just cause problems. The only thing you gain is a slight optimization in calculating perimeter by turning two multiplications and an addition into a single multiplication which really wouldn't have an effect on performance unless you were doing that calculation millions of times per second. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Sat, Nov 1, 2014 at 8:24 AM, sohcahto...@gmail.com wrote: I've never heard of the Circle-Ellipse problem, and my first instinct to Rob's post was to ask, why would you want to sub-class Rectangle into a Square class? A square is just a special case of a Rectangle. Attempting that kind of sub-classing would just cause problems. The only thing you gain is a slight optimization in calculating perimeter by turning two multiplications and an addition into a single multiplication which really wouldn't have an effect on performance unless you were doing that calculation millions of times per second. Yep. A square is indeed a special case of rectangle (and a circle is a special case of ellipse), so it would make sense to have an is_square() method (or isSquare or squarep or whatever you want to call it). The hairiness of subclassing either to make the other means it's an unideal example. In fact, I would say the Python @property decorator is less well suited to an inheritance situation than to a chronological change. This used to be a simple attribute, now it has validation/formatting/logging/whatever. But it's hard to come up with an example to illustrate this cleanly for a student. Personally, I'd be inclined to skip properties altogether; learn about them later, much later, and only if you actually need them. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Fri, 31 Oct 2014 14:24:11 -0700 (PDT) sohcahto...@gmail.com wrote: On Friday, October 31, 2014 1:51:23 PM UTC-7, Chris Angelico wrote: On Sat, Nov 1, 2014 at 4:43 AM, Rob Gaddi rgaddi@technologyhighland.invalid wrote: Define a Square class, subclassed from Rectangle. Use getters/setters to enforce that the length and width must be equal. Confirm that length and width remain locked, and that perimeter() and area() work correctly. Here we go again... http://en.wikipedia.org/wiki/Circle-ellipse_problem Square and Rectangle are just as obviously the other way around in the hierarchy, and it's wrong whichever way you do it. Not a good example. ChrisA I've never heard of the Circle-Ellipse problem, and my first instinct to Rob's post was to ask, why would you want to sub-class Rectangle into a Square class? A square is just a special case of a Rectangle. Attempting that kind of sub-classing would just cause problems. The only thing you gain is a slight optimization in calculating perimeter by turning two multiplications and an addition into a single multiplication which really wouldn't have an effect on performance unless you were doing that calculation millions of times per second. As a practical tool? Entirely and completely useless, no doubt about it. But it's easily understood as an example, even if the reason that a Square is a subclass of Rectangle is because I said so. For this specific exercise, a Square is a subclass of Rectangle because the point of Rectangle is to demonstrate that extraneous get/set functions are completely unnecessary in Python. The point of Square is to demonstrate that get/set functions can be useful in certain circumstances where you need to implement non-trivial behaviors, such as making the width property into an alias for the length true data member. As a learning tool for thinking about inheritance hierarchies it's kind of rubbish. But then again, most inheritance hierarchies are ambigious at best, which is why has a is often a better choice than is a. -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Sat, Nov 1, 2014 at 8:40 AM, Rob Gaddi rgaddi@technologyhighland.invalid wrote: For this specific exercise, a Square is a subclass of Rectangle because the point of Rectangle is to demonstrate that extraneous get/set functions are completely unnecessary in Python. The point of Square is to demonstrate that get/set functions can be useful in certain circumstances where you need to implement non-trivial behaviors, such as making the width property into an alias for the length true data member. As the Wikipedia article explains, this has its own consequences. A reasonable test suite for Rectangle would quite probably fail if given a Square. Hence my belief that this makes for a less-than-ideal example. But I can't think of *any* good example of @property for a tutorial. ANY. As a learning tool for thinking about inheritance hierarchies it's kind of rubbish. But then again, most inheritance hierarchies are ambigious at best, which is why has a is often a better choice than is a. Agreed. There certainly are times when is a is the right choice, but there are a lot more times when has a is the better choice. Usually, when I subclass, it's because I want to tweak the behaviour of an existing type (for instance, subclass int and change its repr() to return hex(self)), so it really truly is a superclass, in every way except that one tiny change. Otherwise, new type with a member. Much simpler. Much safer. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
Seymore4Head wrote: The course is free. You can't beat the price. It is only for a few more weeks. But if it's teaching you things that are blatantly wrong in relation to Python, it may be doing more harm than good. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Fri, 31 Oct 2014 18:57:31 -0400, Dennis Lee Bieber wlfr...@ix.netcom.com wrote: On Fri, 31 Oct 2014 14:18:44 -0400, Seymore4Head Seymore4Head@Hotmail.invalid declaimed the following: On Fri, 31 Oct 2014 10:43:19 -0700, Rob Gaddi rgaddi@technologyhighland.invalid wrote: Define a Square class, subclassed from Rectangle. Use getters/setters to enforce that the length and width must be equal. Confirm that length and width remain locked, and that perimeter() and area() work correctly. class Rectangle: def __init__(self,length,width): self.length=length self.width=width def area(self): return self.length*self.width def perimeter(self): return 2*self.length+2*self.width class Square(Rectangle): def set_side (self): if self.length!=self.width: Where's the rest of that -- not to mention you called it set_side but never pass a side into it for use. -=-=-=-=-=-=-=- class Rectangle(object): def __init__(self, length, width=None): self.length = length if width is None: self.width = length else: self.width = width def area(self): return self.length * self.width def perimeter(self): return 2 * (self.length + self.width) Thanks for posting that. I had given up on trying it. I follow the changes you made up this point. I will have to think some more to get the rest of this. The way you provided a catch for not having a width, I don't understand the purpose of a Square subclass. Couldn't side just be length? BTW I am willing to forget any mention of getter/setter. We can just pretend that never happened. class Square(Rectangle): def __init__(self, side): self.side = side def _getLength(self): return self.side def _getWidth(self): return self.side def _setLength(self, vlu): self.side = vlu def _setWidth(self, vlu): self.side = vlu length = property(_getLength, _setLength) width = property(_getWidth, _setWidth) aRect = Rectangle(2, 4) print aRect.length, aRect.width, aRect.area(), aRect.perimeter() aRect.length = 9 print aRect.length, aRect.width, aRect.area(), aRect.perimeter() aSqr = Square(3) print aSqr.side, aSqr.length, aSqr.width, aSqr.area(), aSqr.perimeter() aSqr.length = 4 print aSqr.side, aSqr.length, aSqr.width, aSqr.area(), aSqr.perimeter() aSqr.width = 5 print aSqr.side, aSqr.length, aSqr.width, aSqr.area(), aSqr.perimeter() aSqr.side = 7 print aSqr.side, aSqr.length, aSqr.width, aSqr.area(), aSqr.perimeter() -=-=-=-=-=-=-=-=- Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\Wulfraed\Documentscd Python Progs C:\Users\Wulfraed\Documents\Python Progsproperty2.py 2 4 8 12 9 4 36 26 3 3 3 9 12 4 4 4 16 16 5 5 5 25 20 7 7 7 49 28 C:\Users\Wulfraed\Documents\Python Progs -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Fri, 31 Oct 2014 19:22:13 -0400, Seymore4Head Seymore4Head@Hotmail.invalid wrote: On Fri, 31 Oct 2014 18:57:31 -0400, Dennis Lee Bieber wlfr...@ix.netcom.com wrote: On Fri, 31 Oct 2014 14:18:44 -0400, Seymore4Head Seymore4Head@Hotmail.invalid declaimed the following: On Fri, 31 Oct 2014 10:43:19 -0700, Rob Gaddi rgaddi@technologyhighland.invalid wrote: Define a Square class, subclassed from Rectangle. Use getters/setters to enforce that the length and width must be equal. Confirm that length and width remain locked, and that perimeter() and area() work correctly. class Rectangle: def __init__(self,length,width): self.length=length self.width=width def area(self): return self.length*self.width def perimeter(self): return 2*self.length+2*self.width class Square(Rectangle): def set_side (self): if self.length!=self.width: Where's the rest of that -- not to mention you called it set_side but never pass a side into it for use. -=-=-=-=-=-=-=- class Rectangle(object): def __init__(self, length, width=None): self.length = length if width is None: self.width = length else: self.width = width def area(self): return self.length * self.width def perimeter(self): return 2 * (self.length + self.width) Thanks for posting that. I had given up on trying it. I follow the changes you made up this point. I will have to think some more to get the rest of this. The way you provided a catch for not having a width, I don't understand the purpose of a Square subclass. Couldn't side just be length? BTW I am willing to forget any mention of getter/setter. We can just pretend that never happened. I took your instruction and change it to this: That answers my own question. Thanks again class Rectangle(object): def __init__(self, length, width=None): self.length = length if width is None: self.width = length else: self.width = width def area(self): return self.length * self.width def perimeter(self): return 2 * (self.length + self.width) class Square(Rectangle): def area(self): return self.length * self.width def perimeter(self): return 2 * (self.length + self.width) a=Rectangle(3,5) print (a.area()) print (a.perimeter()) b=Rectangle(5,7) print (b.area()) print (b.perimeter()) c=Square(4) print (c.area()) print (c.perimeter()) -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
Gregory Ewing wrote: Seymore4Head wrote: The course is free. You can't beat the price. It is only for a few more weeks. But if it's teaching you things that are blatantly wrong in relation to Python, it may be doing more harm than good. Like all good Pythonistas[1], we hate Java and think that getter/setter methods are pointless. But come on, they're not *wrong*, as in incorrect. They do the job they're supposed to do, at the expense of an awkward interface. Using properties is *exactly the same as Java getters/setters*, except that the interface is less awkward. And there are times when using getters and setters is the right choice. Properties should only be used for quite lightweight calculations, because attribute access is supposed to be fast. If your calculation is complex, time-consuming or might fail, using a property is a bad idea and you should use an explicit getter method, possibly with a setter if needed. There are lots of things in Python which are written as getter methods or functions, rather than attributes or properties. E.g.: py (23).bit_length() 5 py len(hello world!) # calls __len__ method 12 Files have quite a few examples. fileno, isatty and writable could all be written as read-only properties, and seek/tell could be written as a file.position property. But they're not, they're written as methods. [1] Except for Jythonistas, who are allowed to enjoy using Java. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
Dennis Lee Bieber wrote: What you are being taught is NOT PYTHON. Of course it is. It uses Python syntax, Python terminology, and the Python compiler. It might not be the preferred Python idiom or best practice, but it's still Python code. Exaggeration does not help anyone, it just makes us look like religious fanatics. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Thu, 30 Oct 2014 16:16:51 -0400 Seymore4Head Seymore4Head@Hotmail.invalid wrote: class pet: def set_age(self,age): self.age=age def get_age(self): return self.age pax=pet pax.set_age(4) Traceback (most recent call last): File C:\Functions\test.py, line 18, in module pax.set_age(4) TypeError: set_age() missing 1 required positional argument: 'age' I am trying to pass 4 as the age. Obviously I am doing it wrong. The reason your call is missing the positional argument is that 4 is being assigned to self, rather than to age, so there is no age. This is because you are trying to call a function of the class object, rather than a function of an instance of the class. pax=pet() -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Thursday, October 30, 2014 1:19:57 PM UTC-7, Seymore4Head wrote: class pet: def set_age(self,age): self.age=age def get_age(self): return self.age pax=pet pax.set_age(4) Traceback (most recent call last): File C:\Functions\test.py, line 18, in module pax.set_age(4) TypeError: set_age() missing 1 required positional argument: 'age' I am trying to pass 4 as the age. Obviously I am doing it wrong. The line `pax=pet` doesn't create an instance of your pet class, it creates essentially a copy of the class definition. You need `pax=pet()` Or preferably, `pax = pet()`. The spaces are optional, but they make it more readable. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Thu, 30 Oct 2014 13:34:04 -0700, Rob Gaddi rgaddi@technologyhighland.invalid wrote: On Thu, 30 Oct 2014 16:16:51 -0400 Seymore4Head Seymore4Head@Hotmail.invalid wrote: class pet: def set_age(self,age): self.age=age def get_age(self): return self.age pax=pet pax.set_age(4) Traceback (most recent call last): File C:\Functions\test.py, line 18, in module pax.set_age(4) TypeError: set_age() missing 1 required positional argument: 'age' I am trying to pass 4 as the age. Obviously I am doing it wrong. The reason your call is missing the positional argument is that 4 is being assigned to self, rather than to age, so there is no age. This is because you are trying to call a function of the class object, rather than a function of an instance of the class. pax=pet() Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Thu, 30 Oct 2014 13:33:01 -0700 (PDT), sohcahto...@gmail.com wrote: On Thursday, October 30, 2014 1:19:57 PM UTC-7, Seymore4Head wrote: class pet: def set_age(self,age): self.age=age def get_age(self): return self.age pax=pet pax.set_age(4) Traceback (most recent call last): File C:\Functions\test.py, line 18, in module pax.set_age(4) TypeError: set_age() missing 1 required positional argument: 'age' I am trying to pass 4 as the age. Obviously I am doing it wrong. The line `pax=pet` doesn't create an instance of your pet class, it creates essentially a copy of the class definition. You need `pax=pet()` Or preferably, `pax = pet()`. The spaces are optional, but they make it more readable. Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On 10/30/2014 01:16 PM, Seymore4Head wrote: class pet: def set_age(self,age): self.age=age def get_age(self): return self.age pax=pet pax.set_age(4) Traceback (most recent call last): File C:\Functions\test.py, line 18, in module pax.set_age(4) TypeError: set_age() missing 1 required positional argument: 'age' I am trying to pass 4 as the age. Obviously I am doing it wrong. You have already received the answer -- pax=pet should be pax=pet(), but I have a simple side-comment about style. It is common Python convention to capitalize class names, IOW make this class Pet instead of class pet. This is convention not a requirement, but it does help distinguish class names from ordinary variable names -- especially to others reading your code (as well as yourself a few days later). ;-) -=- Larry -=- -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Thu, 30 Oct 2014 14:28:19 -0700, Larry Hudson org...@yahoo.com wrote: On 10/30/2014 01:16 PM, Seymore4Head wrote: class pet: def set_age(self,age): self.age=age def get_age(self): return self.age pax=pet pax.set_age(4) Traceback (most recent call last): File C:\Functions\test.py, line 18, in module pax.set_age(4) TypeError: set_age() missing 1 required positional argument: 'age' I am trying to pass 4 as the age. Obviously I am doing it wrong. You have already received the answer -- pax=pet should be pax=pet(), but I have a simple side-comment about style. It is common Python convention to capitalize class names, IOW make this class Pet instead of class pet. This is convention not a requirement, but it does help distinguish class names from ordinary variable names -- especially to others reading your code (as well as yourself a few days later). ;-) -=- Larry -=- I try to take typing shortcuts and it bites me in the behind. Good suggestion Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes
On Thursday, October 30, 2014 2:37:54 PM UTC-7, Seymore4Head wrote: On Thu, 30 Oct 2014 14:28:19 -0700, Larry Hudson org...@yahoo.com wrote: On 10/30/2014 01:16 PM, Seymore4Head wrote: class pet: def set_age(self,age): self.age=age def get_age(self): return self.age pax=pet pax.set_age(4) Traceback (most recent call last): File C:\Functions\test.py, line 18, in module pax.set_age(4) TypeError: set_age() missing 1 required positional argument: 'age' I am trying to pass 4 as the age. Obviously I am doing it wrong. You have already received the answer -- pax=pet should be pax=pet(), but I have a simple side-comment about style. It is common Python convention to capitalize class names, IOW make this class Pet instead of class pet. This is convention not a requirement, but it does help distinguish class names from ordinary variable names -- especially to others reading your code (as well as yourself a few days later). ;-) -=- Larry -=- I try to take typing shortcuts and it bites me in the behind. Good suggestion Thanks A shortcut is the fastest way to get somewhere you weren't going. Python makes programming very easy (Compared to C/C++ and many other languages), but there are still a lot of shortcuts you can't make. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes and the command line
- Original Message - From: Seymore4Head Seymore4Head@Hotmail.invalid To: python-list@python.org Sent: Monday, 27 October, 2014 3:27:18 AM Subject: Classes and the command line I am trying to learn classes. I am currently using Python 2.7 at the command line. If you try to type commands at the command line and make the slightest mistake you have to start over. I was trying to copy and paste these instructions into the command prompt. http://en.wikibooks.org/wiki/Python_Programming/Classes class Foo: ... def setx(self, x): ... self.x = x ... def bar(self): ... print self.x There is really no way to do that without pasting line by line is there and adding deleting spaces? And if you use spaces and tabs, they are not the same. You could use Ipython http://ipython.org/, if you're familiar with the python shell you won't get lost as it's quite the same with a lot of features added. One of them is the %paste magic function, it will paste your clipboard taking care of the indentation for you. JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes and the command line
On Sun, 26 Oct 2014 23:32:08 -0400, Seymore4Head wrote: On Mon, 27 Oct 2014 14:06:11 +1100, Ben Finney ben+pyt...@benfinney.id.au wrote: Seymore4Head Seymore4Head@Hotmail.invalid writes: I am trying to learn classes. I am currently using Python 2.7 at the command line. (I think you mean the interactive Python interpreter, or just the Python shell.) Since you are learning Python, I will strongly recommend you ignore Python 2 unless it becomes unavoidable. At the moment, it is unavoidable. The instructors are teaching Python 2 so I have to learn Python 2, for now. Instead, learn Python 3 primarily; it is much better because it omits a bunch of legacy behaviour you don't need. If you try to type commands at the [interactive shell] and make the slightest mistake you have to start over. Right. There is line-by-line history, and editing enabled with the readline plug-in. (This is an advantage of using a programmer- friendly operating system, which MS Windows sadly is not.) I was trying to copy and paste these instructions into the [interactive Python shell]. http://en.wikibooks.org/wiki/Python_Programming/Classes class Foo: ... def setx(self, x): ... self.x = x ... def bar(self): ... print self.x There is really no way to do that without pasting line by line is there and adding deleting spaces? And if you use spaces and tabs, they are not the same. Right on all counts. The interactive Python shell is good for very quickly experimenting and demonstrating how Python actually behaves, statement by statement. But as you point out, it is not a good choice for anything more complex. It is a good learning and debugging tool. When you start to write larger units of code, like a class or a function, you can trade immediacy for flexibility: write your code into a text editor, save it to a file foo.py, then run that code at a separate OS command prompt by invoking python foo.py in the terminal. That way, you can continue to adjust and tweak the code as you learn how your changes affect the code. You do need to keep invoking the actions separately edit the file, save the file, run the file with Python but this is what's needed when you want to run a program more than once anyway, so it's a good step to take. Find a good, *general-purpose* programmer's editor. Preferably licensed under free software terms, with a strong community supporting it, and available on all major platforms for when you switch to a decent programmer-friendly operating system. I am actually using Notepad some too. Thanks notepad is not a programmer friendly editor personally I like Geany as it is nice and basic but still offers a lot of programmer friendly features such as syntax highlighting, a small terminal window which I use to run the interactive terminal for testing quick one-liners pressing f5 will save run the current file being edited. www.geany.org Notepad+ is also often suggested along with many other programmer editors/ Integrated development environments (IDE). I would advise you keep away from the more complex IDE's for now as you do not want to overload your learning requirements. -- Who the mad would destroy, first they make Gods. -- Bernard Levin -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes and the command line
On Mon, Oct 27, 2014 at 10:17 PM, alister alister.nospam.w...@ntlworld.com wrote: Notepad+ is also often suggested along with many other programmer editors/ Integrated development environments (IDE). That would be Notepad++, and yes, it's fairly well recommended. It's based on the same edit component as SciTE, another good editor (and the one I use). ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes and the command line
On Sun, 26 Oct 2014 23:32:08 -0400, Seymore4Head Seymore4Head@Hotmail.invalid wrote: On Mon, 27 Oct 2014 14:06:11 +1100, Ben Finney ben+pyt...@benfinney.id.au wrote: Seymore4Head Seymore4Head@Hotmail.invalid writes: I am trying to learn classes. I am currently using Python 2.7 at the command line. (I think you mean the interactive Python interpreter, or just the Python shell.) Since you are learning Python, I will strongly recommend you ignore Python 2 unless it becomes unavoidable. At the moment, it is unavoidable. The instructors are teaching Python 2 so I have to learn Python 2, for now. Instead, learn Python 3 primarily; it is much better because it omits a bunch of legacy behaviour you don't need. If you try to type commands at the [interactive shell] and make the slightest mistake you have to start over. Right. There is line-by-line history, and editing enabled with the readline plug-in. (This is an advantage of using a programmer-friendly operating system, which MS Windows sadly is not.) I was trying to copy and paste these instructions into the [interactive Python shell]. http://en.wikibooks.org/wiki/Python_Programming/Classes class Foo: ... def setx(self, x): ... self.x = x ... def bar(self): ... print self.x There is really no way to do that without pasting line by line is there and adding deleting spaces? And if you use spaces and tabs, they are not the same. Right on all counts. The interactive Python shell is good for very quickly experimenting and demonstrating how Python actually behaves, statement by statement. But as you point out, it is not a good choice for anything more complex. It is a good learning and debugging tool. When you start to write larger units of code, like a class or a function, you can trade immediacy for flexibility: write your code into a text editor, save it to a file foo.py, then run that code at a separate OS command prompt by invoking python foo.py in the terminal. That way, you can continue to adjust and tweak the code as you learn how your changes affect the code. You do need to keep invoking the actions separately edit the file, save the file, run the file with Python but this is what's needed when you want to run a program more than once anyway, so it's a good step to take. Find a good, *general-purpose* programmer's editor. Preferably licensed under free software terms, with a strong community supporting it, and available on all major platforms for when you switch to a decent programmer-friendly operating system. I am actually using Notepad some too. Thanks I meant Notepad ++ -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes and the command line
On 10/26/2014 11:24 PM, Chris Angelico wrote: On Mon, Oct 27, 2014 at 2:18 PM, Rustom Mody rustompm...@gmail.com wrote: On Monday, October 27, 2014 8:40:48 AM UTC+5:30, Chris Angelico wrote: You can get block-by-block history by using Idle. I find that fairly convenient for manipulating class/function definitions. ChrisA Umm... Nice! A bit inconsistent in that the '...' does not appear. But thats good; makes copy|cut-pasting from interpreter to file a mostly trivial operation. One of the differences between console interpreter and Idle Shell is that the former is line oriented whereas Shell is statement oriented. In the console interpreter, you cannot edit a line after it is entered. In Shell, you can edit any line until you enter an entire statment. Similarly, c. i. history recalls a line at a time. Recalling an multiline statment has to be done a line at a time, in order. Shell history recalls an entire statement, even if multiple lines (this is what Chris means by 'blocks'). Explaining this difference as the reason for no ... is on my todo list. It's inconsistent only because the default sys.ps2 is those dots, which aren't necessary in Idle. You could make it consistent by simply changing sys.ps2. Nope. User code is executed in the user process. Its only effect on the Idle process is to write to stdout or stderr for display. There is tracker issue about letting users change sys.ps1 *in the Idle process*, but it would have to be through the menu or config dialog. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes and the command line
On 10/26/2014 11:28 PM, Seymore4Head wrote: I am going to be flexible on IDLE in the near future, but I wanted to try it the old fashion way. I already know using IDLE is better, but I am not sure using IDLE will invoke Python 2 and I am not sure how to change that at the moment. Currently, Idle executes user code with the same interpreter it is running on. Now that user code is executed in a subprocess, there is the possibility of using a different python in the subprocess. But this is for the future. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes and the command line
On Tue, Oct 28, 2014 at 3:08 PM, Terry Reedy tjre...@udel.edu wrote: It's inconsistent only because the default sys.ps2 is those dots, which aren't necessary in Idle. You could make it consistent by simply changing sys.ps2. Nope. User code is executed in the user process. Its only effect on the Idle process is to write to stdout or stderr for display. There is tracker issue about letting users change sys.ps1 *in the Idle process*, but it would have to be through the menu or config dialog. I knew that, honest I did... umm, let's just pretend I was talking about changing sys.ps2 in the console interpreter. Yeah. Because I totally knew that changing it in Idle wouldn't work. Plus, I tested it before posting, like everyone should. Honest! Changing it in the console interpreter does work, though. Python 3.5.0a0 (default:301b9a58021c, Oct 2 2014, 09:20:24) [GCC 4.7.2] on linux Type help, copyright, credits or license for more information. import sys sys.ps2= def x(): pass And if you want consistency, that's a good way to get it. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes and the command line
Seymore4Head Seymore4Head@Hotmail.invalid writes: I am trying to learn classes. I am currently using Python 2.7 at the command line. (I think you mean “the interactive Python interpreter”, or just “the Python shell”.) Since you are learning Python, I will strongly recommend you ignore Python 2 unless it becomes unavoidable. Instead, learn Python 3 primarily; it is much better because it omits a bunch of legacy behaviour you don't need. If you try to type commands at the [interactive shell] and make the slightest mistake you have to start over. Right. There is line-by-line history, and editing enabled with the “readline” plug-in. (This is an advantage of using a programmer-friendly operating system, which MS Windows sadly is not.) I was trying to copy and paste these instructions into the [interactive Python shell]. http://en.wikibooks.org/wiki/Python_Programming/Classes class Foo: ... def setx(self, x): ... self.x = x ... def bar(self): ... print self.x There is really no way to do that without pasting line by line is there and adding deleting spaces? And if you use spaces and tabs, they are not the same. Right on all counts. The interactive Python shell is good for very quickly experimenting and demonstrating how Python actually behaves, statement by statement. But as you point out, it is not a good choice for anything more complex. It is a good learning and debugging tool. When you start to write larger units of code, like a class or a function, you can trade immediacy for flexibility: write your code into a text editor, save it to a file ‘foo.py’, then run that code at a separate OS command prompt by invoking ‘python foo.py’ in the terminal. That way, you can continue to adjust and tweak the code as you learn how your changes affect the code. You do need to keep invoking the actions separately – edit the file, save the file, run the file with Python – but this is what's needed when you want to run a program more than once anyway, so it's a good step to take. Find a good, *general-purpose* programmer's editor. Preferably licensed under free software terms, with a strong community supporting it, and available on all major platforms for when you switch to a decent programmer-friendly operating system. -- \“When you go in for a job interview, I think a good thing to | `\ ask is if they ever press charges.” —Jack Handey | _o__) | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes and the command line
On Monday, October 27, 2014 8:00:04 AM UTC+5:30, Seymore4Head wrote: I am trying to learn classes. I am currently using Python 2.7 at the command line. Why not idle? And if in general you are at python 3, why 2.7 here? There are enough factor to learn ( and get confused)! Please dont add new ones gratuitously! If you try to type commands at the command line and make the slightest mistake you have to start over. I was trying to copy and paste these instructions into the command prompt. http://en.wikibooks.org/wiki/Python_Programming/Classes class Foo: ... def setx(self, x): ... self.x = x ... def bar(self): ... print self.x There is really no way to do that without pasting line by line is there and adding deleting spaces? And if you use spaces and tabs, they are not the same. http://imgur.com/a/XTkAm Let me repeat and elaborate what I have already told you -- - you should write mostly expressions at the interpreter prompt - you should write definitions in the file Rough distinctions: 1. Things like 1+2, lst.append(3) etc are expressions 2. Things like assignment, if, while are statements 3. class and def statements are special; and called definitions Notes a. theres an inclusion 1 'sits inside' 2 'sits inside' 3 b. Its easiest if you try 1 in the interpreter; 3 in the python file c. 2 is a bit clumsy. Short ones can be tried at the interpreter Longer than 3 (max 4) lines should go into files. May require a bit of thought how to package a statement into a definition to try out d. 2 is clumsy in files for a different reason; you will need to write prints judiciously e. Since def itself goes into class, if youve not yet worked out a comfortable 'tryin-out' model, stay with defs for now In short: For a while people here have been advising you Use the Interpreter Now I will add slightly to that: Use the interpreter in idle, along with a python file -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes and the command line
On Mon, Oct 27, 2014 at 2:06 PM, Ben Finney ben+pyt...@benfinney.id.au wrote: Right. There is line-by-line history, and editing enabled with the “readline” plug-in. (This is an advantage of using a programmer-friendly operating system, which MS Windows sadly is not.) You can get block-by-block history by using Idle. I find that fairly convenient for manipulating class/function definitions. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes and the command line
On Monday, October 27, 2014 8:40:48 AM UTC+5:30, Chris Angelico wrote: On Mon, Oct 27, 2014 at 2:06 PM, Ben Finney wrote: Right. There is line-by-line history, and editing enabled with the readline plug-in. (This is an advantage of using a programmer-friendly operating system, which MS Windows sadly is not.) You can get block-by-block history by using Idle. I find that fairly convenient for manipulating class/function definitions. ChrisA Umm... Nice! A bit inconsistent in that the '...' does not appear. But thats good; makes copy|cut-pasting from interpreter to file a mostly trivial operation. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes and the command line
On Mon, Oct 27, 2014 at 2:18 PM, Rustom Mody rustompm...@gmail.com wrote: On Monday, October 27, 2014 8:40:48 AM UTC+5:30, Chris Angelico wrote: On Mon, Oct 27, 2014 at 2:06 PM, Ben Finney wrote: Right. There is line-by-line history, and editing enabled with the readline plug-in. (This is an advantage of using a programmer-friendly operating system, which MS Windows sadly is not.) You can get block-by-block history by using Idle. I find that fairly convenient for manipulating class/function definitions. ChrisA Umm... Nice! A bit inconsistent in that the '...' does not appear. But thats good; makes copy|cut-pasting from interpreter to file a mostly trivial operation. It's inconsistent only because the default sys.ps2 is those dots, which aren't necessary in Idle. You could make it consistent by simply changing sys.ps2. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes and the command line
On Monday, October 27, 2014 8:48:52 AM UTC+5:30, Rustom Mody wrote: On Monday, October 27, 2014 8:40:48 AM UTC+5:30, Chris Angelico wrote: On Mon, Oct 27, 2014 at 2:06 PM, Ben Finney wrote: Right. There is line-by-line history, and editing enabled with the readline plug-in. (This is an advantage of using a programmer-friendly operating system, which MS Windows sadly is not.) You can get block-by-block history by using Idle. I find that fairly convenient for manipulating class/function definitions. ChrisA Umm... Nice! A bit inconsistent in that the '...' does not appear. But thats good; makes copy|cut-pasting from interpreter to file a mostly trivial operation. No not quite so nice... Does not respect the current indent level :-( [which an emacs 'rectangle' copy-paste will] -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes and the command line
Your message showed up as unavailable on my server I have to cut and paste Google Groups to reply. (I am going to change news servers probably tomorrow to try to fix that) So the quoting is going to be bad. Why not idle? And if in general you are at python 3, why 2.7 here? There are enough factor to learn ( and get confused)! Please don't add new ones gratuitously! --- I am taking two courses in Python 2 so I think I am going to forget using Python 3 until I finish the courses. One of the course instructors suggests we try the command like way. Your other explanations on the distinctions are helpful, but for now I am going with Python 2. Final answer. :) (A few more weeks) They are teaching Python 2. I have to use Python 2 to learn it. Thanks I am going to be flexible on IDLE in the near future, but I wanted to try it the old fashion way. I already know using IDLE is better, but I am not sure using IDLE will invoke Python 2 and I am not sure how to change that at the moment. -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes and the command line
On Mon, 27 Oct 2014 14:06:11 +1100, Ben Finney ben+pyt...@benfinney.id.au wrote: Seymore4Head Seymore4Head@Hotmail.invalid writes: I am trying to learn classes. I am currently using Python 2.7 at the command line. (I think you mean the interactive Python interpreter, or just the Python shell.) Since you are learning Python, I will strongly recommend you ignore Python 2 unless it becomes unavoidable. At the moment, it is unavoidable. The instructors are teaching Python 2 so I have to learn Python 2, for now. Instead, learn Python 3 primarily; it is much better because it omits a bunch of legacy behaviour you don't need. If you try to type commands at the [interactive shell] and make the slightest mistake you have to start over. Right. There is line-by-line history, and editing enabled with the readline plug-in. (This is an advantage of using a programmer-friendly operating system, which MS Windows sadly is not.) I was trying to copy and paste these instructions into the [interactive Python shell]. http://en.wikibooks.org/wiki/Python_Programming/Classes class Foo: ... def setx(self, x): ... self.x = x ... def bar(self): ... print self.x There is really no way to do that without pasting line by line is there and adding deleting spaces? And if you use spaces and tabs, they are not the same. Right on all counts. The interactive Python shell is good for very quickly experimenting and demonstrating how Python actually behaves, statement by statement. But as you point out, it is not a good choice for anything more complex. It is a good learning and debugging tool. When you start to write larger units of code, like a class or a function, you can trade immediacy for flexibility: write your code into a text editor, save it to a file foo.py, then run that code at a separate OS command prompt by invoking python foo.py in the terminal. That way, you can continue to adjust and tweak the code as you learn how your changes affect the code. You do need to keep invoking the actions separately edit the file, save the file, run the file with Python but this is what's needed when you want to run a program more than once anyway, so it's a good step to take. Find a good, *general-purpose* programmer's editor. Preferably licensed under free software terms, with a strong community supporting it, and available on all major platforms for when you switch to a decent programmer-friendly operating system. I am actually using Notepad some too. Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Classes and the command line
On Mon, 27 Oct 2014 14:10:01 +1100, Chris Angelico ros...@gmail.com wrote: On Mon, Oct 27, 2014 at 2:06 PM, Ben Finney ben+pyt...@benfinney.id.au wrote: Right. There is line-by-line history, and editing enabled with the readline plug-in. (This is an advantage of using a programmer-friendly operating system, which MS Windows sadly is not.) You can get block-by-block history by using Idle. I find that fairly convenient for manipulating class/function definitions. ChrisA Thanks BTW I am using XP some and Win7 some too. -- https://mail.python.org/mailman/listinfo/python-list
Re: classes and sub classes?
Jason Friedman wrote: NwInvDb = NetworkInventoryDatabase, yes you are correct, it creates the database handle and makes it ready for use. I am interested in opinions. I for one dislike abbreviations on the theory that programs are read more than they are written. I would probably use this variable name: network_inventory_db_connection = ... And yes, I'm aware that db is an abbreviation. I believe I am following a few Zen principles: Beautiful is better than ugly. Explicit is better than implicit. Readability counts. Special cases aren't special enough to break the rules, Although practicality beats purity. What would others use? inventory_db The rest should be clear from the context. -- http://mail.python.org/mailman/listinfo/python-list
Re: classes and sub classes?
On 2013-04-15, Peter Otten __pete...@web.de wrote: Jason Friedman wrote: NwInvDb = NetworkInventoryDatabase, yes you are correct, it creates the database handle and makes it ready for use. I am interested in opinions. I for one dislike abbreviations on the theory that programs are read more than they are written. I would probably use this variable name: network_inventory_db_connection = ... And yes, I'm aware that db is an abbreviation. I believe I am following a few Zen principles: Beautiful is better than ugly. Explicit is better than implicit. Readability counts. Special cases aren't special enough to break the rules, Although practicality beats purity. What would others use? inventory_db The rest should be clear from the context. How long and descriptive a name is ought to depend on the wideness of its visibility. n might be acceptable in a short comprehension, while network_inventory_db_connection might be apposite for a module-level name. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: classes and sub classes?
NwInvDb = NetworkInventoryDatabase, yes you are correct, it creates the database handle and makes it ready for use. I am interested in opinions. I for one dislike abbreviations on the theory that programs are read more than they are written. I would probably use this variable name: network_inventory_db_connection = ... And yes, I'm aware that db is an abbreviation. I believe I am following a few Zen principles: Beautiful is better than ugly. Explicit is better than implicit. Readability counts. Special cases aren't special enough to break the rules, Although practicality beats purity. What would others use? -- http://mail.python.org/mailman/listinfo/python-list
Re: classes and sub classes?
On 15/04/2013 02:38, Jason Friedman wrote: NwInvDb = NetworkInventoryDatabase, yes you are correct, it creates the database handle and makes it ready for use. I am interested in opinions. I for one dislike abbreviations on the theory that programs are read more than they are written. I would probably use this variable name: network_inventory_db_connection = ... And yes, I'm aware that db is an abbreviation. I believe I am following a few Zen principles: Beautiful is better than ugly. Explicit is better than implicit. Readability counts. Special cases aren't special enough to break the rules, Although practicality beats purity. What would others use? network could be abbreviated to net, inventory to inv (maybe OK in this context; in another context it could an abbreviation for inverse), and connection to con (maybe), giving net_inv_db_con, or net_inv_db_connection. The trick, of course, is to make it clear, but not annoyingly long. Python itself has def, len, and lstrip, not define, length and left_strip. -- http://mail.python.org/mailman/listinfo/python-list
Re: classes and sub classes?
On Tue, 09 Apr 2013 07:50:11 +0200, Morten Guldager wrote: 'Aloha Friends! I'm about to write an API against a huge propitiatory Oracle based network inventory database. The database have many different concepts stored in it's tables, can one concept can span over multiple tables. I would like to write a class for accessing each concept, but only have a single database connection throughout the whole program. Sounds reasonable. I imagine some code along these lines, but cant figure out how to declare the classes that will make it work: # create a connection to the database and perform come basic login and initialization nib = NwInvDb(scott/tiger@ora) # find a device by ip interesting_device = nib.Device.lookup_by_ip(192.168.1.1) What's nib mean? And NwInvDb? I can imagine that the Db at the end stands for Database, but the rest is just word-salad. I can guess that NwInvDb is some sort of database connection. Am I close? In this example I access the concept Device. Should I make the Device class inherit from NwInvDb? Or should I keep them separate? Why are you asking us? We don't know what functionality you expect NwInvDb and Device to have, what they represent, or whether a Device can be meaningfully considered an instance of a NwInvDb, whatever that is. But given my *guess* that NwInvDb represents a database connection, and that Device represents data fetched from that database, then no of course you should not inherit. Inheritance implies an is-a relationship. If you inherit from NwInvDb for Device, that implies: - interesting_device Is-A database; - anywhere you can use a NwInvDb database object, you can use a Device object. And the same would apply to every other concept in the database. That does not sound like a clean and useful design to me. -- Steven -- http://mail.python.org/mailman/listinfo/python-list