Python:更好的设计是让Python对象具有intellisense get all available属性
我的主要目标是为用户提供一个从库中导入的python对象,该对象可以使用点操作访问其所有属性(与intellisense/auto complete一起使用,这一点非常重要)。请参见下面的示例代码 有没有更好的方法来设计这个库?正如您所看到的,可能有多个类,它们非常相似。如果没有Python:更好的设计是让Python对象具有intellisense get all available属性,python,design-patterns,properties,autocomplete,intellisense,Python,Design Patterns,Properties,Autocomplete,Intellisense,我的主要目标是为用户提供一个从库中导入的python对象,该对象可以使用点操作访问其所有属性(与intellisense/auto complete一起使用,这一点非常重要)。请参见下面的示例代码 有没有更好的方法来设计这个库?正如您所看到的,可能有多个类,它们非常相似。如果没有\uuu init\uuu,我怎么能传递“parent”值,因为我只想使用全点操作访问值/属性,而不需要()。基本上,我只希望用户执行类似于Sample.parentA.john的操作,而不是Sample().paren
\uuu init\uuu
,我怎么能传递“parent”值,因为我只想使用全点操作访问值/属性,而不需要()
。基本上,我只希望用户执行类似于Sample.parentA.john
的操作,而不是Sample().parentA().john
之类的操作
这可能相当混乱,尤其是当它变得非常嵌套时。我尝试使用点操作读取/创建一个表并访问字典的成员(有点像,但问题是,对象不会真正自动填充或无法使用intellisense,因此用户仍然需要知道结构或可用属性,因此它不能真正满足我的需要
在XML结构中实现整个数据可能会更干净,并且有一个代码生成和对象,可以让intellisense检测可用属性,但我似乎无法让它与intellisense一起工作。有点像上面使用dictionary的点操作
简而言之,我想要一个支持intellisense/autofill的python对象来帮助用户获得可用的属性(可以嵌套)最后,我真的需要用户选择的所有选项的字符串表示。选项的含义是Sample.parentA.steve.joe
user真正选择了选项parentA、steve和joe。当然,有些选项仅可用,具体取决于选择的“parent”选项
mylibrary.py:
class GrandchildSarah():
name = "ParentA_ChildSteve_GrandchildSarah"
class GrandchildJoeA():
name = "ParentA_ChildSteve_GrandchildJoe"
class GrandchildJoeB():
name = "ParentB_ChildSteve_GrandchildJoe"
class ChildSteveA():
name = "ParentA_ChildSteve"
sarah = GrandchildSarah
joe = GrandchildJoeA
class ChildSteveB():
name = "ParentB_ChildSteve"
joe = GrandchildJoeB
class ChildJohn():
name = "ParentA_ChildJohn"
class ParentA():
name = "ParentA"
john = ChildJohn
steve = ChildSteveA
class ParentB():
name = "ParentB"
steve = ChildSteveB
class Sample():
parentA = ParentA
parentB = ParentB
def check(exp, obj):
if isinstance(obj, str):
print(f"expected: {exp} actual: {obj}")
elif isinstance(obj, type):
print(f"expected: {exp} actual: {obj.name}")
else:
print(f"expected: {exp} actual: {obj}")
main.py:
from mylibrary import Sample, check
a = Sample.parentA # can be completed using auto complete
check("ParentA", a)
a = Sample.parentA.john # can be completed using auto complete
check("ParentA_ChildJohn", a)
a = Sample.parentA.steve # can be completed using auto complete
check("ParentA_ChildSteve", a)
a = Sample.parentA.steve.sarah # can be completed using auto complete
check("ParentA_ChildSteve_GrandchildSarah", a)
a = Sample.parentA.steve.joe # can be completed using auto complete
check("ParentA_ChildSteve_GrandchildJoe", a)
a = Sample.parentB # can be completed using auto complete
check("ParentB", a)
a = Sample.parentB.steve # can be completed using auto complete
check("ParentB_ChildSteve", a)
a = Sample.parentB.steve.joe # can be completed using auto complete
check("ParentB_ChildSteve_GrandchildJoe", a)
我喜欢你的长篇大论,但我不太确定你想要实现什么…看起来你的代码工作得很好,做了你想要的,对吗?备选方案?也许看看静态方法或元类?但我会坚持你的实现。