Learning #python question 2:

Is there any rhyme or reason behind the different styles of method syntax for objects? I'm trying to understand why you see all these various styles of method invocations, and whether there is an underlying pattern behind whether something is expressed using one syntax or another:

'foo' in a
a & b (for set intersection)
a.union(b) (for set union)
len(a), del(a['foo'])


@vortex_egg many of those are syntactic sugar on top of the underlying class methods, which have a more consistent syntax.

One thing I note: For many objects, a += 'foo' might work, but there's a .add() fallback to be more explicit.

That doesn't really help when you're learning, I know, so I'll also add that the decisions were made for readability wherever possible.

@phildini Thanks that is helpful!

The assumption I was building evidence for is that there is a single consistent underlying method syntax (`a.foo()`), and then a variety of "more readable" alternate syntactic sugars... and that learning materials are presenting me with a wide variety of syntaxes without first presenting a systemic explanation of such (which seems suboptimal to me for learning things systematically).

@vortex_egg yeah, and I can see where that would be helpful for sure. One issue is that Python is an almost-30-year-old language at this point, and has largely tried to maintain backwards syntactic compatibility.

a quick comment: for where a+= 'x' might not work but a.add('x'), it looks like you want to add an element to a Set. Try a |= 'x'. Some might say that does not make so much sense since the __add__ method on a object refers to the plus-operator.
Sign in to participate in the conversation
Wandering Shop

The Wandering Shop is a Mastodon instance initially geared for the science fiction and fantasy community but open to anyone. We want our 'local' timeline to have the feel of a coffee shop at a good convention: tables full of friendly conversation on a wide variety of topics. We welcome everyone who wants to participate, so long as you're willing to abide by our code of conduct.