[英]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.