difference between variables inside and outside of __init__()

前端 未结 10 799
醉酒成梦
醉酒成梦 2020-11-22 17:08

Is there any difference at all between these classes besides the name?

class WithClass ():
    def __init__(self):
        self.value = \"Bob\"
    def my_fu         


        
10条回答
  •  时光说笑
    2020-11-22 17:42

    In Python, a class comes with member functions (methods), class variables, attributes/instance variables (and probably class methods too):

    class Employee:
    
        # Class Variable
        company = "mycompany.com"
    
        def __init__(self, first_name, last_name, position):
            # Instance Variables
            self._first_name = first_name
            self._last_name = last_name
            self._position = position
    
        # Member function
        def get_full_name(self):
            return f"{self._first_name} {self._last_name}"
    

    By creating an instance of the object

    my_employee = Employee("John", "Wood", "Software Engineer")
    

    we essentially trigger __init__ that is going to initialise the instance variables of the newly created Employee. This means that _first_name, _last_name and _position are explicit parameters of the specific my_employee instance.

    Likewise, member functions return information or change the state of a specific instance.


    Now any variable defined outside the constructor __init__ are considered to be class variables. Those variables are shared amongst all the instances of the class.

    john = Employee("John", "Wood", "Software Engineer")
    bob = Employee("Bob", "Smith", "DevOps Engineer0")
    
    print(john.get_full_name())
    print(bob.get_full_name())
    print(john.company)
    print(bob.company)
    
    >>> John Wood
    >>> Bob Smith
    >>> mycompany.com
    >>> mycompany.com
    

    You can also use class methods in order to change the class variable for all the instances of the class. For example:

    @classmethod
    def change_my_companys_name(cls, name):
        cls.company = name
    

    and now change_my_companys_name()

    bob.change_my_companys_name("mynewcompany.com")
    

    will have effect on all the instances of class Employee:

    print(bob.company)
    print(john.company)
    
    >>> mynewcompany.com
    >>> mynewcompany.com
    

提交回复
热议问题