Files
pymol/plugin/cmd_singleton.py
2024-09-07 09:12:14 +08:00

52 lines
1.9 KiB
Python

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@file :base.py
@Description: :pymol cmd 全局单例
@Date :2023/09/24 12:34:33
@Author :lyzeng
@Email :pylyzeng@gmail.com
@version :1.0
'''
# pymol_singleton.py
import sys
from pathlib import Path
from pymol import cmd as pymol_cmd, launch as pymol_launch
from typing import Any
from dataclasses import dataclass, field, InitVar
here = Path(__file__).absolute().parent
sys.path.append(here.as_posix())
from plugin.config import colorp, font, mole, atom
@dataclass
class PyMOLSingleton:
_instance: InitVar[Any] = None # InitVar类型表示这个字段仅用于__post_init__
colorp: type(colorp) = field(default_factory=colorp) # 使用default_factory设置默认值
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super(PyMOLSingleton, cls).__new__(cls)
return cls._instance
def __post_init__(self, _instance):
if _instance is None:
# 绑定pymol.cmd的所有方法到这个单例对象
for attr in dir(pymol_cmd):
if callable(getattr(pymol_cmd, attr)) and not attr.startswith("__"):
setattr(self, attr, getattr(pymol_cmd, attr))
# 初始化配色
self.defcolor()
# 启动PyMOL界面
self.launch()
def defcolor(self):
# 根据self.colorp生成颜色
color_gennerate = map(lambda x: x[0], self.colorp.colors)
list(map(lambda x: self.set_color(*x), color_gennerate)) # 使用self.set_color而不是cmd.set_color
self.set_color(*self.colorp.grey1) # 使用self.set_color而不是cmd.set_color
def launch(self):
pymol_launch() # 使用pymol的launch函数来启动PyMOL界面
# 创建单例对象并暴露给其他模块
cmd = PyMOLSingleton()