zoukankan      html  css  js  c++  java
  • 私有变量为何传给了子类?

    #Python33Libsite-packagesdjangocontribauthmodels.py
    class UserManager(BaseUserManager):
    
        def _create_user(self, username, email, password,
                         is_staff, is_superuser, **extra_fields):
            """
            Creates and saves a User with the given username, email and password.
            """
            now = timezone.now()
            if not username:
                raise ValueError('The given username must be set')
            email = self.normalize_email(email)
            user = self.model(username=username, email=email,
                              is_staff=is_staff, is_active=True,
                              is_superuser=is_superuser, last_login=now,
                              date_joined=now, **extra_fields)
            user.set_password(password)
            user.save(using=self._db)
            return user
    
        def create_user(self, username, email=None, password=None, **extra_fields):
            return self._create_user(username, email, password, False, False,
                                     **extra_fields)
    
        def create_superuser(self, username, email, password, **extra_fields):
            return self._create_user(username, email, password, True, True,
                                     **extra_fields)

    不太 明白,

    self._db明明是一个私有变量,怎么可能来自于父类呢?如果不来自父类,子类又没有在任何地方定义它

    看来是记错了:
    Python中所有的类成员(包括数据成员)都是公共的 ,所有的方法都是有效的。
    只有一个例外:如果你使用的数据成员名称以双下划线前缀 比如__privatevar,Python的名称管理体系会有效地把它作为私有变量。
    这样就有一个惯例,如果某个变量只想在类或对象中使用,就应该以单下划线前缀。而其他的名称都将作为公共的,可以被其他类/对象使用。记住这只是一个惯例,并不是Python所要求的(与双下划线前缀不同)。
    同样,注意__del__方法与destructor的概念类似。
  • 相关阅读:
    apache的并发
    PHP 文件上传
    打包备份3天
    dz改写CSS
    linux cifs自动挂载远程windows硬盘或文件夹
    C++面向对象
    "i++"和"++i"
    《程序员面试宝典》一个程序
    《程序员面试宝典》强制转换,内存地址
    《程序员面试宝典》编程技巧--位运算
  • 原文地址:https://www.cnblogs.com/xiangnan/p/3505972.html
Copyright © 2011-2022 走看看