开发者

Alternative ways to instantiate a class in Python

I am currently writing my python classes and instantiate them like this

class calculations开发者_开发技巧_class():
    def calculate(self):
        return True

Calculations = calculations_class()

I was wondering if I was doing this correctly, or if there were any other ways to instantiate them. Thanks!


Apart from the naming convention issue which other answers have correctly pointed out, you're basically fine: calling a class is indeed by far the most common way of instantiating that class. If you need any per-instance initialization (most typically setting some instance-attributes to initial values), be sure to define an __init__ method that performs it:

class Calculations(object):
  def __init__(self):
    self.running_total = 0  # or w/ever
  def calculate(self):
    ...

calc = Calculations()

The other, rare ways of instantiating a class typically occur when you want to bypass the initialization part for some reason (e.g., in the course of de-serializing an instance from some file, database, or communication from other processes -- the pickle module is a good example of needing such advanced approaches). I don't think you should worry about them at all at this stage of your Python learning experience.


Well, class names tend to be capitalized (and camelcase) and instance names tend to be lowercase, but further that's the way to go.

class CalculationsClass():
    def calculate(self):
        return True

my_calc_instance = CalculationsClass()


That is correct.


This is the right way. Only thing you should do differently: class names should start with an uppercase letter, and variables with a lowercase one.


I tend to use the following format:

class CCalculations():        #Classes always begin with "C"
    def __init__(self):
        self.foo = 0
        self.fooBar = 0       #Variables use camelCase

    def DoCalculations(self): #Methods use uppercase
        return true

    def getFoo(self): 
        return self.foo       #getters and setters use camelCase

The reasons for this are varied:

  1. Putting "C" in front of the class name easily separates what is a class and what is a method/function. This is especially useful if you're using a good IDE (I use WingIDE). So all of your classes are located in one spot because all of them start with C. Also, it makes code more readable since you know for sure you are instancing a class and not calling a function.

  2. Using capital letters for regular methods and camelCase for getters and setters means that more important regular methods are not cluttering up the namespace with gets/sets. So within the class, since things go in ASCII-betical order, your real methods come first and your getters and setters last.

  3. Class names should be nouns. Methods should be verbs that describe actions the noun can do. Attributes should be nouns that describe how the noun looks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜