換句話說,我想創建Thing存在于Some_Category. 我還希望Thing該類繼承自__Thing_Abstract,它存在于 的本地范圍之外Some_Category。我不確定我應該如何去做。
class __Thing_Abstract:
def __init__(self,var):
self.var=var
class Some_Category:
class Thing(__Thing_Abstract):
def printVar(self): print(self.var)
def getType(self): return type(self.var)
我確實理解“兩個尾隨下劃線”書寫約定 ( __) 不會使 Python 類成為私有的。例如,如果我要使用實體化變數A_Class的方法創建類,然后嘗試訪問它,我會撰寫如下內容:__init____data_A_Class__data
class A_Class:
def __init__(self):
self.__data="Data"
print(A_Class()._A_Class__data)
此示例回傳Data.
我假設在第一個示例中,Python 在嘗試繼承時會首先查看全域范圍__Thing_Abstract,類似地在某個方法中參考另一個類時。
class A_Class1:
def __init__(self,data):
self.data=data
class A_Class2:
def method(data):
print(A_Class1(data).data)
A_Class2.method("Random Data")
這個例子“作業正常”并列印Random Data.
但是,當我運行第一個示例時,它回傳以下錯誤:
Traceback (most recent call last):
File "/home/user/test.py", line 6, in <module>
class Some_Category:
File "/home/user/test.py", line 7, in Some_Category
class Thing(__Thing_Abstract):
NameError: name '_Some_Category__Thing_Abstract' is not defined
我想知道我將如何解決這個問題。感謝您提供的所有幫助。
uj5u.com熱心網友回復:
通過將類設定__Thing_Abstract為的類屬性Some_Category
class __Thing_Abstract:
def __init__(self,var):
self.var=var
class Thing(__Thing_Abstract):
def __init__(self, var):
super().__init__(var)
def printVar(self): print(self.var)
def getType(self): return type(self.var)
class Some_Category:
Thing = Thing
print(Some_Category.Thing.__name__)
#Thing
print(Some_Category.Thing.__bases__[0].__name__)
#__Thing_Abstract
print(Some_Category.Thing(9).printVar)
#<bound method Thing.printVar of <__main__.Thing object at 0x7fc0cd238fa0>>
或者,要繞過范圍問題,您可以使用globals()
class __Thing_Abstract:
def __init__(self,var):
self.var=var
class Some_Category:
class Thing(globals()['__Thing_Abstract']):
def printVar(self): print(self.var)
def getType(self): return type(self.var)
...在這一點上,您應該問自己是否使用字典跟蹤所有__-classes 會更好:my__cls = {__Thing_Abstract: __Thing_Abstract, ...}
提示:使用裝飾器,您可以以更優雅的方式實作這一目標......但有很多可能性
[來自評論] 這是一個制作自定義字典以跟蹤__-classes 的基本示例。注意my_clsandmy__cls_updater應該在__-classes 之前定義。
my__cls = {} # keep track of all __-classes
def my__cls_updater(cls):
if not cls.__name__.startswith('__'):
print('...hey that s not a __-class!')
return cls
my__cls.update({cls.__name__: cls}) # update thge global dictionary
return cls
@my__cls_updater # <-- each __-class should be preceed by the decorator call
class __Thing_Abstract:
def __init__(self,var):
self.var=var
class Some_Category:
class Thing(my__cls['__Thing_Abstract']):
def printVar(self): print(self.var)
def getType(self): return type(self.var)
“優雅”有點主觀,但希望至少有用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/493251.html
標籤:Python python-3.x 班级 遗产
