Alternative constructors naming convention

W

Will McGugan

Hi,

Is there a naming convention regarding alternative constructors? ie
static methods where __new__ is called explicity. I use lower_case for
methods in general, but thought maybe CamelCase would be better for
alternative contstructors to distinguish them from methods...

So which is better?

c = Color.FromHtml(r, g, b)

c = Color.from_html(r, g, b)


Will McGugan
 
B

Bruno Desthuilliers

Will said:
Hi,

Is there a naming convention regarding alternative constructors? ie
static methods where __new__ is called explicity. I use lower_case for
methods in general, but thought maybe CamelCase would be better for
alternative contstructors to distinguish them from methods...

Well... They are still methods, aren't they ?-)

I don't remember any specific guideline, but FWIW, dict.from_keys() is
an "alternative constructor".

My 2 cents.
 
S

Steven Bethard

Will said:
Is there a naming convention regarding alternative constructors? ie
static methods where __new__ is called explicity.

Are you really using staticmethod and calling __new__? It's often much
easier to use classmethod, e.g.::

class Color(object):
...
@classmethod
def from_html(cls, r, g, b):
...
# convert r, g, b to normal constructor args
...
# call normal constructor
return cls(...)

And FWIW, I use lower_with_underscores for alternate constructors, not
CamelCase.

STeVe
 
W

Will McGugan

Steven said:
Are you really using staticmethod and calling __new__? It's often much
easier to use classmethod, e.g.::

class Color(object):
...
@classmethod
def from_html(cls, r, g, b):
...
# convert r, g, b to normal constructor args
...
# call normal constructor
return cls(...)

I could use that for some things, but often I can avoid an intermediate
step by bypassing the class constructor altogether...
And FWIW, I use lower_with_underscores for alternate constructors, not
CamelCase.

Seems to be the consensus. I think I'll stick_to_it!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top