What would be a best practice to name the class attributes and its methods (functions).
class Base():
def __init__(self):
self.name = 'My Name'
def print_this(self):
print "Hello"
Create an instance of the class:
a = Base()
Get an idea what methods and attributes available in this class:
print dir(a)
Getting this output:
['__doc__', '__init__', '__module__', 'name', 'print_this']
From reading the names in dir() output it is impossible to see where the variables are (class attributes) and where the methods (class functions).
What naming conventions to use to differentiate the variables from functions (or attrs from methods)?
Methods should be verbs in lowerCamelCase or a multi-word name that begins with a verb in lowercase; that is, with the first letter lowercase and the first letters of subsequent words in uppercase. Local variables, instance variables, and class variables are also written in lowerCamelCase .
In Java, class names generally should be nouns, in title case with the first letter of each separate word capitalized. and interface names generally should be adjectives, in title case with the first letter of each separate word capitalized.
Naming conventions are general rules applied when creating text scripts for software programming. They have many different purposes, such as adding clarity and uniformity to scripts, readability for third-party applications, and functionality in certain languages and applications.
All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_). After the first character, identifiers can have any combination of characters. A keyword cannot be used as an identifier. Most importantly, identifiers are case sensitive.
Methods should generally have a verb in them, eg print_this
, calculate_that
, save
, because they perform some action.
Attributes and properties will just be a bare noun, eg name
, status
, count
as they just contain a value or, in the case of a property, the underlying function should calculate and return a value, without other side-effects.
Your question is vague though:
is it about naming conventions in Python? For this you should refer to the famous PEP8 document
is it about how to distinguish between methods and attributes by looking at their names? for this see my rule of thumb above
is it about how to distinguish between methods and attributes programmatically? In this case you can use the inspect
module to provide a definitive answer, for example:
import inspect
for attr in dir(a):
if inspect.ismethod(getattr(a, attr)):
print '%s is a method' % attr
else:
print '%s is an attribute or property' % attr
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With