繁体   English   中英

为什么我只需要从模块导入子类而不从另一个实例导入它的基类和它的属性?

[英]Why did I need only to import child class from module without importing its base class and its properties from another instance?

Python 速成课程:基于项目的实践编程介绍

读这本书的时候,我有一个疑问。

为什么我只需要从“admin”导入“Admin”?

在我看来,'test.py' 中的第一行代码意味着它只复制了类 'Admin' 的代码。

因此,第二行和第三行代码不会成功运行,因为它没有结束代码块“from user import User”和类“Privileges”的定义。

任何帮助将不胜感激!

测试文件

from admin import Admin  # line 1


my_admin = Admin('Jade', 'Lam', 'male', '22')  # line 2

my_admin.privileges.show_privileges()  # line 3
print('\n')

管理文件

from user import User


class Admin(User):
    def __init__(self, first_name, last_name, sex, age):
        super().__init__(first_name, last_name, sex, age)
        self.privileges = Privileges()


class Privileges():
    def __init__(self):
        self.privileges = ['can add post', 'can delete post',
                           'can ban user']

    def show_privileges(self):
        print("Admin's privileges: ")
        for privilege in self.privileges:
            print("--" + privilege)

用户.py

class User():
    def __init__(self, first_name, last_name, sex, age):
        self.first_name = first_name.title()
        self.last_name = last_name.title()
        self.sex = sex
        self.age = age

    def describe_user(self):
        --snip--

    def greet_user(self):
        --snip--

请参阅下面的示例。

# Consider this module:

# mod1.py:
# some outer level code
# gets executed

pass

# functions get defined but do not execute
# unless called from above


def f1():
    pass


def f2():
    pass


# classes get defined and actually execute but
# if they only have defs, again those get defined
# but don't run.


class A:
    pass


class B:
    pass


class C:
    pass


# now main.py:
# mod1 executes. Every name of mod1 also becomes  available
# under the prefix 'mod1.' This is like creating a mod1 namespace
# in outer scope of main.
import mod1

# mod1 only runs once on imports in this module, so this time it won't
# (it already has).
# While you can still access every name from mod1 using the mod1 prefix
# from the above import, below only the A name is kept in the outer scope
# of main.
from mod1 import A

# If A has dependencies on other mod1 names, that does not matter here.
# Those dependencies were solved on mod1 run, and all the names involved
# were accessed as needed at mod1 runtime. These names are actually in a
# different scope that belongs to mod1.

# After imports, main can have mod1 names in its scope, but mod1 never
# had access to main names. Unless it imports main, something it should
# not do to avoid circular imports.

希望你现在明白了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM