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



Python速成课程:实践,基于项目的入门编程

当我读这本书时,我有一个问题。

为什么我只需要从"Admin"导入"Admin"?

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

因此,第二行和第三行代码不会成功运行,因为它没有结束代码块"来自用户导入用户"和类"特权"的定义。

任何帮助都将不胜感激!

测试.py

from admin import Admin  # line 1

my_admin = Admin('Jade', 'Lam', 'male', '22')  # line 2
my_admin.privileges.show_privileges()  # line 3
print('n')

admin.py

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)

user.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.

希望你现在明白了。

最新更新