Python的内部/嵌套类使我感到困惑.有没有它们无法实现的东西?如果是这样,那是什么东西?
考虑以下Python(在2.x或3.x中运行):
class Outer(object):
pass
class Inner(object):
def __init__(self):
print("Inner.self", self)
o = Outer()
i = o.Inner()
Run Code Online (Sandbox Code Playgroud)
我想o在里面亲自动手Inner.__init__().但:
o成为一个明确的参数Inner.O.Inner和o.Inner成为一个类的对象,不是很奇怪像关闭.你能建议我怎么做到这一点吗?
现在我最好的想法是使用线程本地存储.在我的用例中,每当我构造一个时o.Inner(),我已经在o某个地方的某个方法中,并且添加它不是什么大问题
threading.local()["my o object"] = o
Run Code Online (Sandbox Code Playgroud)
到我的代码.
这让您了解我愿意考虑的堕落程度.
我正在尝试找到一种将文件结构表示为 python 对象的方法,这样我就可以轻松获得特定路径,而不必键入所有字符串。这适用于我的情况,因为我有一个静态文件结构(不变)。
我想我可以将目录表示为类,将目录中的文件表示为类/静态变量。
我希望能够浏览 python 对象,以便它返回我想要的路径,即:
print(FileStructure.details.file1) # root\details\file1.txt
print(FileStructure.details) # root\details
Run Code Online (Sandbox Code Playgroud)
我从下面的代码中得到的是:
print("{0}".format(FileStructure())) # root
print("{0}".format(FileStructure)) # <class '__main__.FileStructure'>
print("{0}".format(FileStructure.details)) # <class '__main__.FileStructure.details'>
print("{0}".format(FileStructure.details.file1)) # details\file1.txt
Run Code Online (Sandbox Code Playgroud)
到目前为止我拥有的代码是......
import os
class FileStructure(object): # Root directory
root = "root"
class details(object): # details directory
root = "details"
file1 = os.path.join(root, "file1.txt") # File in details directory
file2 = os.path.join(root, "file2.txt") # File in details directory
def __str__(self):
return f"{self.root}"
def __str__(self):
return f"{self.root}"
Run Code Online (Sandbox Code Playgroud)
我不想必须实例化该类才能完成这项工作。我的问题是:
我错过了什么,或者这样的事情不可能吗?
class Outer:
def __init__(self, val):
self.__val = val
def __getVal(self):
return self.__val
def getInner(self):
return self.Inner(self)
class Inner:
def __init__(self, outer):
self.__outer = outer
def getVal(self):
return self.__outer.__getVal()
foo = Outer('foo')
inner = foo.getInner()
val = inner.getVal()
print val
Run Code Online (Sandbox Code Playgroud)
我收到此错误消息:
return self.__outer.__getVal()
AttributeError: Outer instance has no attribute '_Inner__getVal'
Run Code Online (Sandbox Code Playgroud) class A(object):
class B(object):
def __getitem__(self, key):
# Obviously not the same self here...
x = self.function_A_needs_as_well(key)
def function_A_needs_as_well(self, value):
pass
Run Code Online (Sandbox Code Playgroud)
我希望这个例子不是太糟糕,至少有点自我解释.有人能告诉我如何从"B级"内部调用"function_A_needs_as_well"吗?