Static variable inheritance in Python

前端 未结 2 991
感情败类
感情败类 2021-02-04 08:12

I\'m writing Python scripts for Blender for a project, but I\'m pretty new to the language. Something I am confused about is the usage of static variables. Here is the piece of

2条回答
  •  清酒与你
    2021-02-04 08:38

    You can access active through the class it belongs to:

    if panelToggle.active:
        # do something
    

    If you want to access the class variable from a method, you could write:

    def am_i_active(self):
        """ This method will access the right *class* variable by
            looking at its own class type first.
        """
        if self.__class__.active:
            print 'Yes, sir!'
        else:
            print 'Nope.'
    

    A working example can be found here: http://gist.github.com/522619


    The self variable (named self by convention) is the current instance of the class, implicitly passed but explicitely recieved.

    class A(object):
    
        answer = 42
    
        def add(self, a, b):
            """ ``self`` is received explicitely. """
            return A.answer + a + b
    
    a = A()
    
    print a.add(1, 2) # ``The instance -- ``a`` -- is passed implicitely.``
    # => 45
    
    print a.answer 
    # => print 42
    

提交回复
热议问题