473,394 Members | 1,706 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

How to get/set class attributes in Python

I'm coming to Python from other programming languages. I like to
hide all attributes of a class and to only provide access to them
via methods. Some of these languages allows me to write something
similar to this

int age( )
{
return theAge
}

void age( x : int )
{
theAge = x
}

(I usually do more than this in the methods). I would like to do
something similar in Python, and I've come up with two ways to do
it: The first one uses the ability to use a variable number of
arguments ... not very nice. The other is better and uses
__setattr__ and __getattr__ in this way:

class SuperClass:
def __setattr__( self, attrname, value ):
if attrname == 'somevalue':
self.__dict__['something'] = value
else:
raise AttributeError, attrname

def __str__( self ):
return str(self.something)

class Child( SuperClass ):
def __setattr__( self, attrname, value ):
if attrname == 'funky':
self.__dict__['fun'] = value
else:
SuperClass.__setattr__( self, attrname, value )

def __str__( self ):
return SuperClass.__str__( self ) + ', ' + str(self.fun)

Is this the "Pythonic" way of doing it or should I do it in a different
way or do I have to use setX/getX (shudder)


Jul 19 '05 #1
32 3296
On Sun, 12 Jun 2005 11:54:52 +0200, Kalle Anke <sk*****@gmail.com> wrote:
I'm coming to Python from other programming languages. I like to
hide all attributes of a class and to only provide access to them
via methods. Some of these languages allows me to write something
similar to this

int age( )
{
return theAge
}

void age( x : int )
{
theAge = x
}

(I usually do more than this in the methods). I would like to do
something similar in Python, and I've come up with two ways to do
it: The first one uses the ability to use a variable number of
arguments ... not very nice. The other is better and uses
__setattr__ and __getattr__ in this way:

class SuperClass:
def __setattr__( self, attrname, value ):
if attrname == 'somevalue':
self.__dict__['something'] = value
else:
raise AttributeError, attrname

def __str__( self ):
return str(self.something)

class Child( SuperClass ):
def __setattr__( self, attrname, value ):
if attrname == 'funky':
self.__dict__['fun'] = value
else:
SuperClass.__setattr__( self, attrname, value )

def __str__( self ):
return SuperClass.__str__( self ) + ', ' + str(self.fun)

Is this the "Pythonic" way of doing it or should I do it in a different
way or do I have to use setX/getX (shudder)


I'm totally new to Python myself, but my understanding is that
Jul 19 '05 #2
Kalle Anke wrote:
I'm coming to Python from other programming languages. I like to
hide all attributes of a class and to only provide access to them
via methods. Some of these languages allows me to write something
similar to this

int age( )
{
return theAge
}

void age( x : int )
{
theAge = x
}

(I usually do more than this in the methods).


You can 'hide' you getsetters using a property attribute[1]:
class person(object): ... def __init__(self):
... self.age = 0
... def set_age(self, age):
... print 'set %d' % age
... self.__age = age
... def get_age(self):
... print 'get'
... return self.__age
... age = property(get_age, set_age)
... joe = person() set 0 joe.age = 20 set 20 print joe.age get
20


[1]http://docs.python.org/lib/built-in-funcs.html
Jul 19 '05 #3
On Sun, 12 Jun 2005 03:15:27 -0700, Steve Jorgensen <no****@nospam.nospam>
wrote:

....
Is this the "Pythonic" way of doing it or should I do it in a different
way or do I have to use setX/getX (shudder)


I'm totally new to Python myself, but my understanding is that

....

Oops - I thought I cancelled that post when I relized I was saying nothing,
but somehow, it got posted.
Jul 19 '05 #4
Kalle Anke wrote:
I'm coming to Python from other programming languages. I like to
hide all attributes of a class and to only provide access to them
via methods.


I'm pretty fond of this format for setting up class properties:

class Klass(object):
def propname():
def fget: pass
def fset: pass
def fdel: pass
def doc: """pass"""
return locals()
propname = property(**propname())

(Replacing 'pass' in the getters & setters et.al with the actual
functionality you want, of course...)

This method minimises the leftover bindings, effectively leaving the
getter/setter methods bound only to the property, ensuring they're only
called when the property is acted upon.

Incidentally, kudos & thanks to whomever I originally stole it from :)

-alex23

Jul 19 '05 #5
Kalle Anke wrote:
I'm coming to Python from other programming languages. I like to
hide all attributes of a class and to only provide access to them
via methods. (...) Is this the "Pythonic" way of doing it or should I do it in a different
way or do I have to use setX/getX (shudder)


the pythonic way is to use "property" (as others have already explained)
only when is *stricly necessary*. this may clarify things up:

"Python Is Not Java"
<http://dirtsimple.org/2004/12/python-is-not-java.html>

HTH.

--
deelan <http://www.deelan.com>
Jul 19 '05 #6
On Sun, 12 Jun 2005 12:20:29 +0200, tiissa wrote
(in article <42***********************@news.free.fr>):

You can 'hide' you getsetters using a property attribute[1]:

[1]http://docs.python.org/lib/built-in-funcs.html


Thanks, this is exactly what I was looking for
Jul 19 '05 #7
Kalle Anke wrote:
On Sun, 12 Jun 2005 12:20:29 +0200, tiissa wrote
(in article <42***********************@news.free.fr>):
You can 'hide' you getsetters using a property attribute[1]:

[1]http://docs.python.org/lib/built-in-funcs.html

Thanks, this is exactly what I was looking for


OTOH, I beseech you to consider an attitude transplant :-)

I.e. put your effort into writing code that allows people to do useful
things, rather than opaque guff full of __blahblah__ that stops them
from doing dopey or evil things they're usually smart enough or
righteous enough not to do anyway.

BTW, what do you think of this:

sys.maxint = -12345

Cheers & HTH,
John

Jul 19 '05 #8
On Sun, 12 Jun 2005 13:59:27 +0200, deelan wrote
(in article <jr*******************@news.edisontel.com>):
the pythonic way is to use "property" (as others have already explained)
only when is *stricly necessary*. this may clarify things up:


Thanks for the link (although Java was only one of the languages I was
thinking of).

Anyway, I got another "problem" (read: being used to do it like this in other
languages). I'm used to use statically typed languages and for me one of the
advantages is that I can be sure that a parameter is of a certain type. So in
Java I could write

void doSomething( data : SomeClass ){ ... }

and I would be sure at compile time that I would only get SomeClass objects
as parameters into the method.

In learning Python I've understood that I should write code in such a way
that it can handle different data and this is fine with me. But what if I
have a class where different attributes should only have values of a certain
type and everything else is an error.

For example, if I have an class that defines three attributes: first and last
name plus email address. The only valid data types for the first two are
strings and for the last an EmailAddress class.

How should I handle this in Python?

Should I use just don't care (but I'm going to send the data to a database so
I need to ensure that the data is OK)? Should I use 'isinstance' and check
manually? Or should I do something else?

(I've been trying to figure out this and other things but I haven't found
much in books or web sites)

jem
Jul 19 '05 #9
On Sun, 12 Jun 2005 15:35:15 +0200, John Machin wrote
(in article <42**************@lexicon.net>):
OTOH, I beseech you to consider an attitude transplant :-)
;-)
I.e. put your effort into writing code that allows people to do useful
things, rather than opaque guff full of __blahblah__ that stops them
from doing dopey or evil things they're usually smart enough or
righteous enough not to do anyway.
I'm just trying to protect myself from myself :-) No, I'm playing around with
different ways of doing things, trying to learn Python and how do things in a
proper "pythonic" way.

In this case I'm going to have a class with some properties that are going to
be stored in a database, I don't want to read all the properties everytime I
recreate the object from the database but I still want to give the impression
that the attributes exists and is available. So my idea was to "hide" the
actual database stuff ...
BTW, what do you think of this:

sys.maxint = -12345


I don't really understand what you're meaning.

jem
Jul 19 '05 #10
On Sun, 12 Jun 2005 15:35:46 +0200,
Kalle Anke <sk*****@gmail.com> wrote:
In learning Python I've understood that I should write code in such a
way that it can handle different data and this is fine with me. But
what if I have a class where different attributes should only have
values of a certain type and everything else is an error. For example, if I have an class that defines three attributes: first
and last name plus email address. The only valid data types for the
first two are strings and for the last an EmailAddress class. How should I handle this in Python? Should I use just don't care (but I'm going to send the data to a
database so I need to ensure that the data is OK)? Should I use
'isinstance' and check manually? Or should I do something else?


One key phrase here is "duck typing": if it walks like a duck, and
swims like a duck, and quacks like a duck, then it's a duck, or at least
you can assume it's a duck. For example:

def put_something( file_open_for_writing, something ):
file_open_for_writing.write( str( something ) )

I don't care if file_open_for_writing is "really a file," as long it has
a "write" method that writes a string somewhere.

The other key phrase is "we're all adults here": if I import sin from
the math module and pass it a unicode string, I get what I deserve.

In lower-level methods/functions, I usually just assume that parameters
are correct, and let the higher-level code catch any exceptions that
occur becuase it (the higher-level code) messed up and passed the wrong
kind of parameter. For example, UI code *has* to check things that
users type, but once that happens, there's no need for my program to
recheck every parameter on every function call all the way down. Either
everything works, or that same UI code catches and logs a TypeError or
ValueError or KeyError exception and asks the user what to do next.

Regards,
Dan

--
Dan Sommers
<http://www.tombstonezero.net/dan/>
Jul 19 '05 #11
"alex23" wrote:
Kalle Anke wrote:
I'm coming to Python from other programming languages. I like to
hide all attributes of a class and to only provide access to them
via methods.


I'm pretty fond of this format for setting up class properties:

class Klass(object):
def propname():
def fget: pass
def fset: pass
def fdel: pass
def doc: """pass"""
return locals()
propname = property(**propname())

(Replacing 'pass' in the getters & setters et.al with the actual
functionality you want, of course...)

This method minimises the leftover bindings, effectively leaving the
getter/setter methods bound only to the property, ensuring they're only
called when the property is acted upon.

Incidentally, kudos & thanks to whomever I originally stole it from :)

-alex23


And a slight improvement in readability IMHO (for python 2.4+) is the
following recipe:
http://aspn.activestate.com/ASPN/Coo.../Recipe/410698.
Using the Property decorator, the property declaration above becomes:

class Klass(object):
@Property # <--- the capitalized 'P' is not a typo
def propname():
'''Documentation'''
def fget: pass
def fset: pass
def fdel: pass

The Property decorator peeks automagically the fget, fset, fdel and
__doc__ from the property's locals(), instead of having the property
return locals() explicitly. Also, it doesn't break when the property
defines local variables other than [fget, fset, fdel, doc].

George

Jul 19 '05 #12
Kalle Anke wrote:
On Sun, 12 Jun 2005 13:59:27 +0200, deelan wrote
(in article <jr*******************@news.edisontel.com>):

void doSomething( data : SomeClass ){ ... }

and I would be sure at compile time that I would only get SomeClass objects
as parameters into the method.


Being an untyped language, Python does not require you to enforce types.
However, for those that require such functionality, you can get away
with using the "assert" statement. For example, if I wanted to make sure
my function foo was only given instances of class Bar, I'd write
something like:
class Bar: pass
def foo(bar): .... assert isinstance(bar, Bar), "argument is not of type Bar"
.... print "argument must be of type Bar"
.... bar = Bar()
foo(bar) argument must be of type Bar foo(123) Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in foo
AssertionError: argument is not of type Bar


Chris
Jul 19 '05 #13
On Sun, 12 Jun 2005 14:40:26 +0000, Chris Spencer wrote:
Being an untyped language, Python does not require you to enforce types.
However, for those that require such functionality, you can get away
with using the "assert" statement.


Assuming that Python isn't executed with the optimize switch, which
disables assert.

$ python -O
Python 2.3.3 (#1, May 7 2004, 10:31:40)
[GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
py>
py>
py> def tester(x):
.... assert type(x) == type(0)
.... print "%s is an integer." % x
....
py> tester(3)
'3 is an integer'
py> tester("hello")
'hello is an integer'
Jul 19 '05 #14
Kalle Anke <sk*****@gmail.com> writes:

[snap]
sys.maxint = -12345


I don't really understand what you're meaning.


He meant None = 1 :>
Jul 19 '05 #15

"Peter Dembinski" <pd***@gazeta.pl> schrieb im Newsbeitrag
news:87************@hector.domek...
| Kalle Anke <sk*****@gmail.com> writes:
|
| [snap]
|
| >> sys.maxint = -12345
| >
| > I don't really understand what you're meaning.
|
| He meant None = 1 :>

I'm sure you know that has become a no-no in Python 2.4+ ;)
None = 1 SyntaxError: assignment to None

--
Vincent Wehren



Jul 19 '05 #16
On Sun, 12 Jun 2005 15:35:46 +0200, Kalle Anke wrote:
Anyway, I got another "problem" (read: being used to do it like this in other
languages). I'm used to use statically typed languages and for me one of the
advantages is that I can be sure that a parameter is of a certain type. So in
Java I could write

void doSomething( data : SomeClass ){ ... }

and I would be sure at compile time that I would only get SomeClass objects
as parameters into the method.

In learning Python I've understood that I should write code in such a way
that it can handle different data and this is fine with me. But what if I
have a class where different attributes should only have values of a certain
type and everything else is an error.

For example, if I have an class that defines three attributes: first and last
name plus email address. The only valid data types for the first two are
strings and for the last an EmailAddress class.

How should I handle this in Python?

Should I use just don't care (but I'm going to send the data to a database so
I need to ensure that the data is OK)? Should I use 'isinstance' and check
manually? Or should I do something else?


As you have worked out, Python doesn't do automatic type-checking for you.
But if you really do need type-checking, you can do it yourself with
isinstance() and/or type(). It isn't forbidden :-)

Or, you can try just coercing the data you have to the type you want. eg
instead of testing to see if obj is an integer, you might do:

try:
obj = int(obj)
except:
raise TypeError("can't convert to integer")
insert_in_database(obj)

This may be appropriate for your application.

Another method that is sometimes useful: you are expecting an instance of
Waterfowl class, but actually you are happy to use duck-typing: if it
looks like a duck, swims like a duck, and quacks like a duck, it is
close-enough to a duck:

def process_waterfowl(duck):
"""do things to an instance of Waterfowl, or equivalent"""
try:
look, swim, quack = duck.look, duck.swim, duck.quack
except AttributeError:
raise TypeError("object is not a waterfowl")
# process any object that has look, swim and quack attributes
# as if it were a waterfowl
duck.look()
duck.swim()
duck.quack()
--
Steven.

Jul 19 '05 #17
"vincent wehren" <vi*****@visualtrans.de> writes:
"Peter Dembinski" <pd***@gazeta.pl> schrieb im Newsbeitrag
news:87************@hector.domek...
| Kalle Anke <sk*****@gmail.com> writes:
|
| [snap]
|
| >> sys.maxint = -12345
| >
| > I don't really understand what you're meaning.
|
| He meant None = 1 :>

I'm sure you know that has become a no-no in Python 2.4+ ;)


Yep. Still waiting for delegalisation of others :>
Jul 19 '05 #18
Chris Spencer a écrit :
Kalle Anke wrote:
On Sun, 12 Jun 2005 13:59:27 +0200, deelan wrote
(in article <jr*******************@news.edisontel.com>):

void doSomething( data : SomeClass ){ ... }

and I would be sure at compile time that I would only get SomeClass
objects as parameters into the method.

Being an untyped language, Python does not require you to enforce types.


Nope. Python *is* typed. But it doesnt confuse implementation with semantic.
However, for those that require such functionality, you can get away
with using the "assert" statement. For example, if I wanted to make sure
my function foo was only given instances of class Bar, I'd write
something like:
>>> class Bar: pass
>>> def foo(bar): ... assert isinstance(bar, Bar), "argument is not of type Bar"
... print "argument must be of type Bar"

...
>>> bar = Bar()
>>> foo(bar) argument must be of type Bar >>> foo(123) Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in foo
AssertionError: argument is not of type Bar >>>


And *this* is highly unpythonic. And un-OO too, since it makes foo()
dependant on *class* Bar, when it should most probably be enough that it
only depends on (probably part of) the *interface* of class Bar.

Suppose I want to adapt my own class Baaz so it's compatible with Bar.
Now I *must* make the adapter a subclass of Bar (and then depends on
Bar's *implementation*) when it only needs to expose the same (probably
subset of) interface.

Except for exceptions (please pardon the pun), one most usually don't
have to worry about the real class of an object. In 5 years programming
Python, I only had to check for the type of an object a couple of times,
and each time only for more genericity (I mostly needed to dispatch on
some 'generic types' like string-like, sequence-like, map-like,
numeric-like, callable, and others), and this was never used as a way to
restrict the possible types (exceptions are good enough for this).

Jul 19 '05 #19
Bruno Desthuilliers wrote:
And *this* is highly unpythonic. And un-OO too, since it makes foo()
dependant on *class* Bar, when it should most probably be enough that it
only depends on (probably part of) the *interface* of class Bar.


I was providing the original poster with a simple way to ensure
appropriate type. You can assert whatever aspect you wish. If you want
to ensure compatibility with some other property simply use "assert
blah" subsituting blah for whatever test you wish to perform (e.g.
assert MyInterface.implementedBy(bar) to test for interface implementation).
Jul 19 '05 #20
Bruno Desthuilliers <bd*****************@free.quelquepart.fr> writes:

[snap]
Being an untyped language, Python does not require you to enforce
types.


Nope. Python *is* typed. But it doesnt confuse implementation
with semantic.


Python is typed. And its type system may look strange for anyone who
did only Java or C++ programming before :>
Jul 19 '05 #21
Chris Spencer a écrit :
Bruno Desthuilliers wrote:
And *this* is highly unpythonic. And un-OO too, since it makes foo()
dependant on *class* Bar, when it should most probably be enough that
it only depends on (probably part of) the *interface* of class Bar.


I was providing the original poster with a simple way to ensure
appropriate type.


s/appropriate type/specific implementation/

Hint : the appropriate type for print >> XXX is "whatever has a
'write(anything_that_can_be_coerced_to_a_string)' method".
Jul 19 '05 #22
Bruno Desthuilliers wrote:
Chris Spencer a écrit :
I was providing the original poster with a simple way to ensure
appropriate type.

s/appropriate type/specific implementation/

Hint : the appropriate type for print >> XXX is "whatever has a
'write(anything_that_can_be_coerced_to_a_string)' method".


Certainly, although now I think you're splitting hairs over my
terminology. Let's synchronize our wording with a point made in the
Python docs. Section 2.1 of the Library Reference recommends that the
builtin function isinstance() be used for testing the object type. Does
this then mean that "type" refers to the class of an object? In which
case, wouldn't "interface" refer to a collection of methods, that when
present in a class create an implementation?

Chris
Jul 19 '05 #23
Peter Dembinski wrote:
Bruno Desthuilliers <bd*****************@free.quelquepart.fr> writes:
Nope. Python *is* typed. But it doesnt confuse implementation
with semantic.

Python is typed. And its type system may look strange for anyone who
did only Java or C++ programming before :>


Of course, in that Python is dynamically typed as opposed to the static
typing of Java or C++. Please excuse my previous mis-wording :)

Chris
Jul 19 '05 #24
Chris Spencer <us****************@spamgourmet.com> writes:
Peter Dembinski wrote:
Bruno Desthuilliers <bd*****************@free.quelquepart.fr> writes:
Nope. Python *is* typed. But it doesnt confuse implementation with
semantic.

Python is typed. And its type system may look strange for anyone
who did only Java or C++ programming before :>


Of course, in that Python is dynamically typed as opposed to the
static typing of Java or C++. Please excuse my previous mis-wording :)


Mis-wording?
Jul 19 '05 #25
Peter Dembinski wrote:
Chris Spencer <us****************@spamgourmet.com> writes:

Peter Dembinski wrote:

Of course, in that Python is dynamically typed as opposed to the
static typing of Java or C++. Please excuse my previous mis-wording :)

Mis-wording?


I previously said Python was "untyped", when it's more accurate to say
"dynamically typed".
Jul 19 '05 #26
Hello!
You can 'hide' you getsetters using a property attribute[1]:


For me, the property attribute is a beast:

class A(object):
def getP(self): return 'A'
p = property(getP)
class A2(A):
def getP(self): return 'A2'
a = A()
a2 = A2()
print a.getP(), a2.getP()
print a.p, a2.p

So, property is instance-level super() tool ;-)

Lg,
AXEL.
--
Gentoo? Debian? RedHat? SuSE? *BSD? Stop the distri-war, make little user!
Jul 19 '05 #27
I really think the problem is that you are trying to use
techniques whose only reason for existing is that they make
up for deficiencies in other languages:

For example, the *reason* for the Java or C++ use of get/set
methods is to allow for the future possibility of needing to
make those operations dynamic. Python solves this by
allowing you to create get/set methods *only when needed*
by using "properties", using exactly the same interface as
provided by ordinary attributes. Thus there is no need to
artificially add get/set methods in the general case.

This results in much cleaner and more concise code.

The *reason* for taking so much care that a variable is of
the right type in classes in C++ or Java is because the
program will crash if they are not. In Python, you would
be better served to:

1) Assume the variables are of a sensible type (not
necessarily the one you expected, though), and provide
exception handling to catch the case where their interface
does not match what you expect.

2) Check for the specific interface methods that you need,
only (if all you plan to do is read from a "file", you
shouldn't worry about whether the "file" object you've been
handed actually has a "write" method or not).
This is often called "duck typing".

3) Use "interfaces" (either from Zope or PyProtocols) to
specify the required *behavior* (not type).

Let's face it -- should it matter if you "are a programmer"
or only if you "can program"? This is the difference in
philosophy behind a dynamically-typed language like
Python and a statically typed one like Java.
--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks http://www.anansispaceworks.com

Jul 19 '05 #28
On Mon, 13 Jun 2005 20:41:48 +0200, Terry Hancock wrote
(in article <ma**************************************@python.o rg>):
1) Assume the variables are of a sensible type (not
necessarily the one you expected, though), and provide
exception handling to catch the case where their interface
does not match what you expect.
The problem I have with this is that I might discover an error at runtime
instead of compile time, this means that I need to really exercise all
possible test cases to make sure that I've covered everything (which of
course is a good thing) but it would be easier to discover this at "compile
time".

(note: I'm not trying to change Python, only that to me statically typing has
it advantages also)
Let's face it -- should it matter if you "are a programmer"
or only if you "can program"? This is the difference in
philosophy behind a dynamically-typed language like
Python and a statically typed one like Java.


I don't really understand what you're meaning (English isn't my native
language as you probably already have discovered)

Jul 19 '05 #29
Kalle Anke <sk*****@gmail.com> writes:
On Mon, 13 Jun 2005 20:41:48 +0200, Terry Hancock wrote
(in article <ma**************************************@python.o rg>):
1) Assume the variables are of a sensible type (not
necessarily the one you expected, though), and provide
exception handling to catch the case where their interface
does not match what you expect.
The problem I have with this is that I might discover an error at runtime
instead of compile time, this means that I need to really exercise all
possible test cases to make sure that I've covered everything (which of
course is a good thing) but it would be easier to discover this at "compile
time".


But static typing only catches *some* of the errors that might
occur. Other errors will occur at run time even with static typing -
so you need to really exercise all possible test cases to make sure
you've covered everything in any case.
(note: I'm not trying to change Python, only that to me statically typing has
it advantages also)


Static typing saves you some time by catching a small subset of
programming errors at compile time. On the other hand, it costs you
time by forcing you to declare a type for - well, everything that
you're going to catch errors for.

It's not clear which cost is larger.

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 19 '05 #30
On Monday 13 June 2005 03:50 pm, Kalle Anke wrote:
On Mon, 13 Jun 2005 20:41:48 +0200, Terry Hancock wrote
(in article <ma**************************************@python.o rg>):
1) Assume the variables are of a sensible type (not
necessarily the one you expected, though), and provide
exception handling to catch the case where their interface
does not match what you expect.


The problem I have with this is that I might discover an error at runtime
instead of compile time, this means that I need to really exercise all
possible test cases to make sure that I've covered everything (which of
course is a good thing) but it would be easier to discover this at "compile
time".


The Python solution to this problem is called "unittest". It is
at least as easy to do unit testing in Python as it is to properly
handle type-checking in C or Java.
Let's face it -- should it matter if you "are a programmer"
or only if you "can program"? This is the difference in
philosophy behind a dynamically-typed language like
Python and a statically typed one like Java.


I don't really understand what you're meaning (English isn't my native
language as you probably already have discovered)


(Actually no, you're quite fluent, AFAICT). I was making
an analogy:

Requiring a variable to be, say, a "float" is like insisting that
only people with the job title "Programmer" be allowed to
see the language documentation.

In both situations, real life will confront you with situations
where you will wish that you had been more tolerant. Lots
of us are not "Programmers", but we do quite a bit of programming.

Likewise, you'll be happier to discover that ints or complex
numbers work with your code too, without having to jump
through hoops to make it happen.

I find the biggest problem coming to Python from a language
like C, C++, or Java is that you overthink things and try to
do them the hard way. A lot of times, you find out that the
"Python way" to do the thing is so blindingly obvious that
it just didn't occur to you that it could be that simple.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks http://www.anansispaceworks.com

Jul 19 '05 #31
On Tue, 14 Jun 2005 06:40:51 +0200, Terry Hancock wrote
(in article <ma**************************************@python.o rg>):
I find the biggest problem coming to Python from a language
like C, C++, or Java is that you overthink things and try to
do them the hard way. A lot of times, you find out that the
"Python way" to do the thing is so blindingly obvious that
it just didn't occur to you that it could be that simple.


It's very possible that this is the case, I'm not experienced enough in
Python yet to have a opinion on this yet. I tend to think in terms of larger
systems with several programmers ... instead of what I'm actually doing
writing code for my own pleasure.

But I'm learning new stuff every day ... so in 6 months I'll probably have an
opinion.
Jul 19 '05 #32
On 6/12/05, Steve Jorgensen <no****@nospam.nospam> wrote:
Oops - I thought I cancelled that post when I relized I was saying nothing,


Would that everyone cancelled their posts when they realised that they
weren't saying anything. ;-)

--
Cheers,
Simon B,
si***@brunningonline.net,
http://www.brunningonline.net/simon/blog/
Jul 19 '05 #33

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: beliavsky | last post by:
What are the pros and cons of defining a method of a class versus defining a function that takes an instance of the class as an argument? In the example below, is it better to be able to write...
50
by: Dan Perl | last post by:
There is something with initializing mutable class attributes that I am struggling with. I'll use an example to explain: class Father: attr1=None # this is OK attr2= # this is wrong...
1
by: Andrew James | last post by:
All, I'm having some trouble with understanding python's importing behaviour in my application. I'm using psyco to optimise part of my code, but I'm not sure whether it inherits throughout the...
166
by: Graham | last post by:
This has to do with class variables and instances variables. Given the following: <code> class _class: var = 0 #rest of the class
0
by: metaperl | last post by:
A Comparison of Python Class Objects and Init Files for Program Configuration ============================================================================= Terrence Brannon bauhaus@metaperl.com...
4
by: Basilisk96 | last post by:
This topic is difficult to describe in one subject sentence... Has anyone come across the application of the simple statement "if (object1's attributes meet some conditions) then (set object2's...
2
by: james_027 | last post by:
hi everyone, I am now in chapter 5 of Dive Into Python and I have some question about it. From what I understand in the book is you define class attributes & data attributes like this in python...
1
by: =?ISO-8859-1?Q?Ricardo_Ar=E1oz?= | last post by:
That is self.__attributes Been reading about the reasons to introduce them and am a little concerned. As far as I understand it if you have a class that inherits from two other classes which...
5
by: Neal Becker | last post by:
After spending the morning debugging where I had misspelled the name of an attribute (thus adding a new attr instead of updating an existing one), I would like a way to decorate a class so that...
11
by: Rafe | last post by:
Hi, I'm working within an application (making a lot of wrappers), but the application is not case sensitive. For example, Typing obj.name, obj.Name, or even object.naMe is all fine (as far as...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.