difference between variables inside and outside of __init__()

前端 未结 10 701
醉酒成梦
醉酒成梦 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:40

    class User(object):
        email = 'none'
        firstname = 'none'
        lastname = 'none'
    
        def __init__(self, email=None, firstname=None, lastname=None):
            self.email = email
            self.firstname = firstname
            self.lastname = lastname
    
        @classmethod
        def print_var(cls, obj):
            print ("obj.email obj.firstname obj.lastname")
            print(obj.email, obj.firstname, obj.lastname)
            print("cls.email cls.firstname cls.lastname")
            print(cls.email, cls.firstname, cls.lastname)
    
    u1 = User(email='abc@xyz', firstname='first', lastname='last')
    User.print_var(u1)
    

    In the above code, the User class has 3 global variables, each with value 'none'. u1 is the object created by instantiating this class. The method print_var prints the value of class variables of class User and object variables of object u1. In the output shown below, each of the class variables User.email, User.firstname and User.lastname has value 'none', while the object variables u1.email, u1.firstname and u1.lastname have values 'abc@xyz', 'first' and 'last'.

    obj.email obj.firstname obj.lastname
    ('abc@xyz', 'first', 'last')
    cls.email cls.firstname cls.lastname
    ('none', 'none', 'none')
    

提交回复
热议问题