When to use static and class methods

Neo Conker

I know there is a lot of topics on this subject, and I've looked at many. However it is still confusing to me when its appropriate to use static and class methods in place of an instance method.

In my example, I'm making a script for the autodesk program maya. One of my modules has a class in it with methods that will generate an object in it, like below:

class Curves(object):
    """Contains methods to generate curves
    """
    @classmethod
    def circle_crv(cls):
        name = mc.circle( nr=(0, 1, 0), c=(0, 0, 0), r=0.5 )
        mc.delete(name, ch=True)
        mc.addAttr(name[0], ln='crvType', dt='string', h=True)
        mc.setAttr(name[0]+'.crvType', 'circle_crv', typ='string', l=True)
        return name[0]

However these will never be directly accessed by an external module. I run all of these methods through a dictionary thats accessed by an external modules (which first searches through an external user dictionary), which is below:

def curve_lib(self, crvtype):
        """Creates a specified curve at origin

        Args:
        crvtype (str): a key to call a function to generate a curve at the
            origin
        """
        userlib = self.usercurve_lib()

        curves_dic = {
            'bendjoint_crv' : self.bendjoint_crv,
            'circle_crv' : self.circle_crv,
            'circlearrow_crv' : self.circlearrow_crv,
            'connectjoint_crv' : self.connectjoint_crv,
            'fktext_crv' : self.fktext_crv,
            'joint_crv' : self.joint_crv,
            'iktext_crv' : self.iktext_crv,
            'cube_crv' : self.cube_crv,
            'quadarrow01_crv' : self.quadarrow01_crv,
            'quadarrow02_crv' : self.quadarrow02_crv,
            'quadarrow03_crv' : self.quadarrow03_crv,
            'quadarrow04_crv' : self.quadarrow04_crv,
            'rootjoint_crv' : self.rootjoint_crv,
            'square_crv' : self.square_crv,
            'switch_crv' : self.switch_crv,
            'triangle_crv' : self.triangle_crv
        }

        if crvtype in userlib:
            name = self.usercurve_lib(crvtype)
        elif crvtype in curves_dic:
            name = curves_dic[crvtype]()
        else:
           raise NameError('Key "%s" not found' %(crvtype))
        return name

So first question, if the method is never accessed from outside of the class or module, does it need to be an instance? And would a static or class method be appropriate in this case, since in this case I dont need seperate instances of this, it just does one thing, and never changes the size or shape, thats resized later.

Next, if i have a method in a class that just performs a simple calculation like below, would a static method be appropriate? Since its just taking input and outputting a single thing every time, is there any reason for it to be an instance?:

class Vectors(object):
    """Contains methods for various vector math functions
    """

    @staticmethod
    def pointLineDist(vec_a, vec_b, vec_c):
        """The distance between the line ab and the point c.

        Args:
        vec_a (float list): First vector to find distance of.
        vec_b (float list): Second vector to find distance of.
        vec_c (float list): Third vector to find distance of.
        """
        ab = dt.Vector(vec_b) - dt.Vector(vec_a)
        ac = dt.Vector(vec_c) - dt.Vector(vec_a)
        length = dt.length(dt.cross(ab, ac)) / dt.length(ab)

        return length

Lastly, I know a lot of people say in these cases, these shouldn't be in the class at all, or something like that, but this is the way I want it, I just want to know more in depth when to use these types of methods.

Lajos Arpad

To put it simply, an instance is an entity, a class is the concept of the entity. For instance, if you have a class Human, then an instance is a human being, while the Human class corresponds to the concept of humanity. For instance, it is pointless to measure the level of pollution generated by a person. Measuring the pollution caused by humanity makes more sense. So, if you have a method called measureGeneratedPollution, it should be static. However, if you have a method called breath, then it is natural that this is an individual action, so breath should be an instance-level method. Instance-level versus static-level is essentially analogous to individual action versus collective action.

Let's see another example for members. Let's consider the class Bird. The birds, collectively do not have a color, so color should be instance-level member. However, birdCount is a collective information, therefore it should be static.

Remember that for members/methods the level (instance or class level) is not determined by the accessibility, but by the subject behind having the attribute or doing the action. So, if we translate this into sentence-logic, then you should write down sentences to yourself while you are making such plans until you get more professional. Sentences, like:

The bird has a color.

There is a number of birds.

Ask questions to yourself:

Who has a color? -> the bird -> singular -> instance Who have the

number? -> the birds -> plural -> collective -> static

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

Java: when to use static methods

From Dev

When extending class with static methods that I don't actually use, will those methods be compiled?

From Dev

Is there a workaround to use static methods by a generic class?

From Dev

Instantiate a class to call a method or use static methods?

From Dev

Is there a workaround to use static methods by a generic class?

From Dev

When should I use static methods?

From Dev

Static Methods ok to use when using parameters?

From Dev

Static class variables are created when Static methods are being called - Java

From Dev

Java: Use Static methods of Parent Class in Child Class

From Dev

Java: Use Static methods of Parent Class in Child Class

From Dev

PHP: When to use Traits and when to use static methods?

From Dev

Class methods - which one to use and when?

From Dev

when to use static method or simple class method?

From Dev

Get the static methods of a class

From Dev

Implementing Static Methods In A Class

From Dev

Is it safe to use static methods on File class in C#?

From Dev

What is the reason you can't use static methods/variables in a class

From Dev

Use of a friend class to hide private static callback methods

From Dev

Why PowerShell use double colon( :: ) to call static methods of a .NET class?

From Dev

Is it OK to use the static utility methods found in the Whitebox class?

From Dev

Java - Only one instance of class: use static methods instead?

From Dev

Does static methods create objects when class is loaded

From Dev

How to understand `JavaScript static methods are also not callable when the class is instantiated`

From Dev

Logging not working when using MyLogger class and static methods

From Dev

:: does not work for static methods when model class is loaded - Codeigniter

From Dev

When to use static variables/methods and when to use instance variables/methods in Java?

From Dev

Using $this when not in object context without the use of static methods

From Dev

Java 8: When the use of Interface static methods becomes a bad practice?

From Dev

When my app is closed Strings are returning null in a class extending BroadcastReceiver when references static methods in another class

Related Related

  1. 1

    Java: when to use static methods

  2. 2

    When extending class with static methods that I don't actually use, will those methods be compiled?

  3. 3

    Is there a workaround to use static methods by a generic class?

  4. 4

    Instantiate a class to call a method or use static methods?

  5. 5

    Is there a workaround to use static methods by a generic class?

  6. 6

    When should I use static methods?

  7. 7

    Static Methods ok to use when using parameters?

  8. 8

    Static class variables are created when Static methods are being called - Java

  9. 9

    Java: Use Static methods of Parent Class in Child Class

  10. 10

    Java: Use Static methods of Parent Class in Child Class

  11. 11

    PHP: When to use Traits and when to use static methods?

  12. 12

    Class methods - which one to use and when?

  13. 13

    when to use static method or simple class method?

  14. 14

    Get the static methods of a class

  15. 15

    Implementing Static Methods In A Class

  16. 16

    Is it safe to use static methods on File class in C#?

  17. 17

    What is the reason you can't use static methods/variables in a class

  18. 18

    Use of a friend class to hide private static callback methods

  19. 19

    Why PowerShell use double colon( :: ) to call static methods of a .NET class?

  20. 20

    Is it OK to use the static utility methods found in the Whitebox class?

  21. 21

    Java - Only one instance of class: use static methods instead?

  22. 22

    Does static methods create objects when class is loaded

  23. 23

    How to understand `JavaScript static methods are also not callable when the class is instantiated`

  24. 24

    Logging not working when using MyLogger class and static methods

  25. 25

    :: does not work for static methods when model class is loaded - Codeigniter

  26. 26

    When to use static variables/methods and when to use instance variables/methods in Java?

  27. 27

    Using $this when not in object context without the use of static methods

  28. 28

    Java 8: When the use of Interface static methods becomes a bad practice?

  29. 29

    When my app is closed Strings are returning null in a class extending BroadcastReceiver when references static methods in another class

HotTag

Archive