示例#1
0
class School(object):
    def __init__(self, name):
        self.name = name


def sayName(self):
    return self.name


s1 = School('Bill')
# 在实例上添加属性
s1.age = 23
print(s1.age, '\n')
# 在实例上添加方法
from types import MethodType
s1.sayName = MethodType(sayName, s1)
print(s1.sayName(), '\n')

s2 = School('Gate')
print(dir(s1), '\n')  # s1上有自定义的name/age属性和sayName方法
print(dir(s2), '\n')  # s2上只有自定义的name属性


def dynamicMethod(self):
    return 'I\'m a dynamic method!'


School.dynamicMethod = dynamicMethod

print(s1.dynamicMethod(), '\n')
print(s2.dynamicMethod(), '\n')
示例#2
0
class Student(object):
    pass


s = Student()
s.name = 'Michael'  # 动态给实例绑定一个属性
print(s.name)


def set_age(self, age):
    self.age = age


from types import MethodType
s.set_age = MethodType(set_age, s)  # 给实例绑定一个方法
s.set_age(25)
print(s.age)

s2 = Student()
# s2.set_age(25)


def set_score(self, score):
    self.score = score


Student.set_score = set_score  # 给类绑定方法
s.set_score(100)
print(s.score)

s2.set_score(99)
示例#3
0
文件: shell.py 项目: samueldg/xonsh
    def singleline(self,
                   auto_suggest=None,
                   enable_history_search=True,
                   multiline=True,
                   **kwargs):
        """Reads a single line of input from the shell. The store_in_history
        kwarg flags whether the input should be stored in PTK's in-memory
        history.
        """
        events.on_pre_prompt.fire()
        env = builtins.__xonsh__.env
        mouse_support = env.get("MOUSE_SUPPORT")
        auto_suggest = auto_suggest if env.get("AUTO_SUGGEST") else None
        refresh_interval = env.get("PROMPT_REFRESH_INTERVAL")
        refresh_interval = refresh_interval if refresh_interval > 0 else None
        complete_in_thread = env.get("COMPLETION_IN_THREAD")
        completions_display = env.get("COMPLETIONS_DISPLAY")
        complete_style = self.completion_displays_to_styles[
            completions_display]

        complete_while_typing = env.get("UPDATE_COMPLETIONS_ON_KEYPRESS")
        if complete_while_typing:
            # PTK requires history search to be none when completing while typing
            enable_history_search = False
        if HAS_PYGMENTS:
            self.styler.style_name = env.get("XONSH_COLOR_STYLE")
        completer = None if completions_display == "none" else self.pt_completer

        get_bottom_toolbar_tokens = self.bottom_toolbar_tokens

        if env.get("UPDATE_PROMPT_ON_KEYPRESS"):
            get_prompt_tokens = self.prompt_tokens
            get_rprompt_tokens = self.rprompt_tokens
        else:
            get_prompt_tokens = self.prompt_tokens()
            get_rprompt_tokens = self.rprompt_tokens()
            if get_bottom_toolbar_tokens:
                get_bottom_toolbar_tokens = get_bottom_toolbar_tokens()

        if env.get("VI_MODE"):
            editing_mode = EditingMode.VI
        else:
            editing_mode = EditingMode.EMACS

        if env.get("XONSH_HISTORY_MATCH_ANYWHERE"):
            self.prompter.default_buffer._history_matches = MethodType(
                _cust_history_matches, self.prompter.default_buffer)
        elif (self.prompter.default_buffer._history_matches
              is not self._history_matches_orig):
            self.prompter.default_buffer._history_matches = self._history_matches_orig

        prompt_args = {
            "mouse_support": mouse_support,
            "auto_suggest": auto_suggest,
            "message": get_prompt_tokens,
            "rprompt": get_rprompt_tokens,
            "bottom_toolbar": get_bottom_toolbar_tokens,
            "completer": completer,
            "multiline": multiline,
            "editing_mode": editing_mode,
            "prompt_continuation": self.continuation_tokens,
            "enable_history_search": enable_history_search,
            "reserve_space_for_menu": 0,
            "key_bindings": self.key_bindings,
            "complete_style": complete_style,
            "complete_while_typing": complete_while_typing,
            "include_default_pygments_style": False,
            "refresh_interval": refresh_interval,
            "complete_in_thread": complete_in_thread,
        }
        if env.get("COLOR_INPUT"):
            if HAS_PYGMENTS:
                prompt_args["lexer"] = PygmentsLexer(pyghooks.XonshLexer)
                style = style_from_pygments_cls(
                    pyghooks.xonsh_style_proxy(self.styler))
            else:
                style = style_from_pygments_dict(DEFAULT_STYLE_DICT)

            prompt_args["style"] = style

            style_overrides_env = env.get("PTK_STYLE_OVERRIDES")
            if style_overrides_env:
                try:
                    style_overrides = Style.from_dict(style_overrides_env)
                    prompt_args["style"] = merge_styles(
                        [style, style_overrides])
                except (AttributeError, TypeError, ValueError):
                    print_exception()

        if env["ENABLE_ASYNC_PROMPT"]:
            # once the prompt is done, update it in background as each future is completed
            prompt_args["pre_run"] = self.prompt_formatter.start_update

        line = self.prompter.prompt(**prompt_args)

        events.on_post_prompt.fire()
        return line
示例#4
0
def ShardingScaler(scaler):
    def unscale_method(self, optimizer):
        if not self._enable:
            return
        param_grads = []
        param_grads_fp16 = []
        param_grads_fp32 = []
        if hasattr(optimizer, "update_slice"):
            optimizer.update_slice()
            optimizer.update_scaler = True

        if getattr(optimizer._optim, '_param_groups', None) and isinstance(
                optimizer._optim._param_groups[0], dict):

            for group in optimizer._optim._param_groups:
                for param in group['params']:
                    if param._grad_ivar() is not None:
                        param_grads.append(param._grad_ivar())
                        if param._grad_ivar().dtype in [
                                core.VarDesc.VarType.FP16, paddle.float16
                        ]:
                            param_grads_fp16.append(param._grad_ivar())
                        else:
                            param_grads_fp32.append(param._grad_ivar())
        else:
            for param in optimizer._optim._parameter_list:
                if param.grad is not None:
                    param_grads.append(param.grad)
                    if param.grad.dtype in [
                            core.VarDesc.VarType.FP16, paddle.float16
                    ]:
                        param_grads_fp16.append(param.grad)
                    else:
                        param_grads_fp32.append(param.grad)

        temp_found_inf_fp16 = to_variable(np.array([0]).astype(np.bool))
        temp_found_inf_fp32 = to_variable(np.array([0]).astype(np.bool))

        device = "cpu" if optimizer.offload else "gpu"
        dev_id = 0 if device == "cpu" else int(
            paddle.get_device().split(":")[1])

        with device_guard(dev_id, device):
            if len(param_grads_fp16):
                _C_ops.check_finite_and_unscale(param_grads_fp16, self._scale,
                                                param_grads_fp16,
                                                temp_found_inf_fp16)
            if len(param_grads_fp32):
                _C_ops.check_finite_and_unscale(param_grads_fp32, self._scale,
                                                param_grads_fp32,
                                                temp_found_inf_fp32)

        self._found_inf = 1 if temp_found_inf_fp16 or temp_found_inf_fp32 else 0
        is_found_inf = paddle.to_tensor([self._found_inf], dtype="int32")

        paddle.distributed.all_reduce(is_found_inf,
                                      op=paddle.distributed.ReduceOp.MAX,
                                      group=optimizer.group)
        self._found_inf = is_found_inf.numpy()[0]

    scaler._unscale = MethodType(unscale_method, scaler)
    return scaler
示例#5
0
    __slots__ = ('age', 'score', 'set_age')
    pass


s = Student()

# s.name = 'mike'
# print s.name


# instance
def set_age(self, age):
    self.age = age


s.set_age = MethodType(set_age, s)
s.set_age(25)
print s.age


# class
def set_score(self, score):
    self.score = score


Student.set_score = set_score

s1 = Student()
s1.set_score(100)
print s1.score
示例#6
0
def bind(
    parser: argparse.ArgumentParser,
    hp_mgr: hpman.HyperParameterManager,
    *,
    inject_actions: Union[bool, List[str]] = True,
    action_prefix: str = config.HP_ACTION_PREFIX_DEFAULT,
    serial_format: str = config.HP_SERIAL_FORMAT_DEFAULT,
    show_defaults: bool = True,
):
    """Bridging the gap between argparse and hpman. This is
        the most important method. Once bounded, hpargparse
        will do the rest for you.

    :param parser: A `class`:`argparse.ArgumentParser` object
    :param hp_mgr: The hyperparameter manager from `hpman`. It is
        usually an 'underscore' variable obtained by `from hpman.m import _`
    :param inject_actions: A list of actions names to inject, or True, to
        inject all available actions. Available actions are 'save', 'load',
        'detail' and 'list'
    :param action_prefix: Prefix for options of hpargparse injected additional
        actions. e.g., the default action_prefix is 'hp'. Therefore, the
        command line options added by :func:`.bind` will be '--hp-save',
        '--hp-load', '--hp-list', etc.
    :param serial_format: One of 'auto', 'yaml' and 'pickle'. Defaults to
        'auto'.  In most cases you need not to alter this argument as long as
        you give the right file extension when using save and load action. To
        be specific, '.yaml' and '.yml' would be deemed as yaml format, and
        '.pickle' and '.pkl' would be seen as pickle format.
    :param show_defaults: Show the default value in help messages.

    :note: pickle is done by `dill` to support pickling of more types.
    """

    # make action list to be injected
    inject_actions = parse_action_list(inject_actions)

    args_set_getter = inject_args(
        parser,
        hp_mgr,
        inject_actions=inject_actions,
        action_prefix=action_prefix,
        serial_format=serial_format,
        show_defaults=show_defaults,
    )

    # hook parser.parse_known_args
    parser._original_parse_known_args = parser.parse_known_args

    def new_parse_known_args(self, *args, **kwargs):
        args, extras = self._original_parse_known_args(*args, **kwargs)

        get_action_value = lambda name: getattr(
            args, "{}_{}".format(action_prefix, name))

        # load saved hyperparameter instance
        load_value = get_action_value("load")
        if "load" in inject_actions and load_value is not None:
            hp_load(load_value, hp_mgr, serial_format)

        # set hyperparameters set from command lines
        old_values = hp_mgr.get_values()
        for k in self.__hpargparse_value_names_been_set():
            v = old_values[k]
            assert hasattr(args, k)
            t = getattr(args, k)
            if isinstance(t, StringAsDefault):
                t = str(t)
            hp_mgr.set_value(k, t)

        save_value = get_action_value("save")
        if "save" in inject_actions and save_value is not None:
            hp_save(save_value, hp_mgr, serial_format)

        hp_list_value = get_action_value("list")
        if "list" in inject_actions and hp_list_value is not None:
            if hp_list_value == "yaml":
                syntax = Syntax(
                    yaml.dump(hp_mgr.get_values()).replace("\n\n", "\n"),
                    "yaml",
                    theme="monokai",
                )
                console = Console()
                console.print(syntax)
            elif hp_list_value == "json":
                syntax = Syntax(json.dumps(hp_mgr.get_values()),
                                "json",
                                theme="monokai")
                console = Console()
                console.print(syntax)
            else:
                assert hp_list_value == "detail", hp_list_value
                hp_list(hp_mgr)

            sys.exit(0)

        hp_detail_value = get_action_value("detail")
        if "detail" in inject_actions and hp_detail_value:
            hp_list(hp_mgr)
            sys.exit(0)

        if inject_actions and get_action_value("exit"):
            sys.exit(0)

        return args, extras

    parser.parse_known_args = MethodType(new_parse_known_args, parser)
    pass


s = Student()
s.name = 'Michael'
print(s.name)


def set_age(self, age):
    self.age = age


from types import MethodType

# 给实例绑定一个方法:
s.set_age = MethodType(set_age, s)
s.set_age(23)
print(s.age)

# 给一个实例绑定的方法,对另一个实例是不起作用的:
s2 = Student()
'''
s2.set_age(25)
'''


# 为了给所有实例都绑定方法,可以给class绑定方法:
def set_score(self, score):
    self.score = score

示例#8
0
 def _create_async_exit_wrapper(cm, cm_exit):
     return MethodType(cm_exit, cm)
 def __getattribute__(__self, __attr):
     #bug: obj = __self.__self__
     obj = object.__getattribute__(__self, '__self__')
     f = getattr(type(obj), __attr)
     return MethodType(f, obj)
示例#10
0
 def add_role(self, role):
     setattr(self, role, MethodType(self._role_template_function(role),
                                    self))
示例#11
0
 def __get__(sf, may_instance, may_owner=None, /):
     if may_instance is None:
         return sf.__func__
     else:
         instance = may_instance
         return MethodType(sf.__func__, instance)
示例#12
0

class Student(object):
    __slots__ = ('name', 'age', 'set_age'
                 )  #通过__slots__变量来限制实例可以添加的属性,它只对当前类的实例起作用,对子类无效
    pass


stu = Student()
stu.name = "Michael"  #动态绑定属性
print(stu.name)


def set_age(self, age):  #定义一个函数作为实例方法
    self.age = age


from types import MethodType
stu.set_age = MethodType(
    set_age, stu)  #实例动态绑定方法,只对该实例有效。绑定方法本质也是绑定属性,若__slots__中没有set_age,则这里报错
stu.set_age(25)
print(stu.age)


def set_score(self, score):
    self.score = score


Student.set_score = set_score  #给class绑定方法,所有实例都可用
stu.set_score(100)
print(stu.score)
示例#13
0
    def perform_error_state(self, input_item, pda):
        raise InputError()

    def invalid_case_print(self):
        print("invalid")

    def valid_case_print(self, closes, opens):
        print("valid")


class InputError(Exception):
    pass


if __name__ == "__main__":
    state0 = State()
    state1 = State()
    state2 = State()
    state3 = State()
    state4 = State()
    error_state = State()
    state0.perform_step = MethodType(PDA.perform_step_for_state_0, state1)
    state1.perform_step = MethodType(PDA.perform_step_for_state_1, state1)
    state2.perform_step = MethodType(PDA.perform_step_for_state_2, state2)
    state3.perform_step = MethodType(PDA.perform_step_for_state_3, state3)
    state4.perform_step = MethodType(PDA.perform_step_for_state_4, state4)
    error_state.perform_step = MethodType(PDA.perform_error_state, error_state)
    pda = PDA('(++-+1101+11001)*(11000+(11110))')
    pda.launch_pda()
示例#14
0
def clean_step_class(cls):
    assert cls.__name__ != "step_name_here"

    text = cls.text or cls.__doc__
    program = cls.program
    hints = cls.hints

    solution = cls.__dict__.get("solution", "")
    assert bool(solution) ^ bool(program)

    if issubclass(cls, ExerciseStep) and not issubclass(cls, MessageStep):
        assert cls.hints, cls

    if solution:
        assert cls.tests
        assert cls.auto_translate_program
        cls.solution = MethodType(solution, "")
        program = clean_program(cls.solution, cls)  # noqa
        cls.solution = cls.wrap_solution(cls.solution)
        if not issubclass(cls, MessageStep) or cls.after_success:
            cls.test_exercise(cls.solution)
    else:
        program = clean_program(program, cls)

    assert program

    if isinstance(hints, str):
        hints = hints.strip().splitlines()
    hints = [t.get(t.hint(cls, i), hint.strip()) for i, hint in enumerate(hints)]

    text = clean_spaces(text)
    assert text
    text = t.get(cls.text_msgid, text)
    text = clean_spaces(text)
    cls.raw_text = text

    if "__program_" in text:
        text = text.replace("__program__", program)
        indented = indent(program, '    ').replace("\\", "\\\\")
        text = re.sub(r" *__program_indented__", indented, text, flags=re.MULTILINE)
    else:
        assert not cls.program_in_text, (
            "Either include __program__ or __program_indented__ in the text, "
            "or set program_in_text = False in the class.",
            cls,
            text,
        )

    assert "__program_" not in text, (cls, text)
    text = clean_spaces(text)

    for special_message in get_special_messages(cls):
        msgstr = clean_spaces(special_message.__doc__ or special_message.text)
        msgstr = t.get(t.special_message_text(cls, special_message), msgstr)
        special_message.text = msgstr
        try:
            special_message.program = t.translate_code(special_message.program)
        except SyntaxError:
            pass

    messages = []
    for name, inner_cls in inspect.getmembers(cls):
        if not (isinstance(inner_cls, type) and issubclass(inner_cls, Step)):
            continue
        assert issubclass(inner_cls, MessageStep)

        inner_cls.tests = inner_cls.tests or cls.tests
        inner_cls.generate_inputs = getattr(cls, "generate_inputs", None)
        inner_cls.page = cls.page
        inner_cls.text_msgid = t.message_step_text(cls, inner_cls)
        clean_step_class(inner_cls)

        original_inner_cls = inner_cls

        # noinspection PyAbstractClass
        class inner_cls(inner_cls, cls):
            __qualname__ = inner_cls.__qualname__
            __module__ = inner_cls.__module__

        inner_cls.__name__ = original_inner_cls.__name__

        messages.append(inner_cls)

        if inner_cls.after_success and issubclass(inner_cls, ExerciseStep):
            cls.check_exercise(inner_cls.solution)

    setattrs(cls,
             text=text,
             program=program,
             messages=messages,
             hints=hints)

    if hints:
        cls.get_solution = get_solution(cls)

    if isinstance(cls.disallowed, Disallowed):
        cls.disallowed = [cls.disallowed]
    for i, disallowed in enumerate(cls.disallowed):
        disallowed.setup(cls, i)

    if cls.expected_code_source:
        getattr(t.Terms, f"expected_mode_{cls.expected_code_source}")
示例#15
0
        def __init__(self, func, *args, **kwargs):
            def member_func(self):
                return func(*args, **kwargs)

            self.func = MethodType(member_func, self)
            self.saved = None
    def __getattribute__(__self, __attr):
        obj = object.__getattribute__(__self, '__self__')
        __attr = f'__{__attr}__'

        f = getattr(type(obj), __attr)
        return MethodType(f, obj)
示例#17
0
def inject_args(
    parser: argparse.ArgumentParser,
    hp_mgr: hpman.HyperParameterManager,
    *,
    inject_actions: List[str],
    action_prefix: str,
    serial_format: str,
    show_defaults: bool,
) -> argparse.ArgumentParser:
    """Inject hpman parsed hyperparameter settings into argparse arguments.
    Only a limited set of format are supported. See code for details.

    :param parser: Use given parser object of `class`:`argparse.ArgumentParser`.
    :param hp_mgr: A `class`:`hpman.HyperParameterManager` object.

    :param inject_actions: A list of actions names to inject
    :param action_prefix: Prefix for hpargparse related options
    :param serial_format: One of 'yaml' and 'pickle'
    :param show_defaults: Show default values

    :return: The injected parser.
    """

    help = ""
    if show_defaults:
        parser.formatter_class = argparse.ArgumentDefaultsHelpFormatter

        # Default value will be shown when using argparse.ArgumentDefaultsHelpFormatter
        # only if a help message is present. This is the behavior of argparse.
        help = " "

    value_names_been_set = set()

    def _make_value_names_been_set_injection(name, func):
        @functools.wraps(func)
        def wrapper(string):
            # when isinstance(default, string),
            # the `parser.parse_args()` will run type(default) automaticly.
            # value_names_been_set should ignore these names.
            if not isinstance(string, StringAsDefault):
                value_names_been_set.add(name)
            return func(string)

        return wrapper

    # add options for collected hyper-parameters
    for k, v in hp_mgr.get_values().items():
        # this is just a simple hack
        option_name = "--{}".format(k.replace("_", "-"))

        if _get_argument_type_by_value(v) == bool:
            # argparse does not directly support bool types.
            parser.add_argument(
                option_name,
                type=_make_value_names_been_set_injection(k, str2bool),
                default=v,
                help=help,
            )
        else:
            if isinstance(v, str):
                # if isinstance(v, str), mark as StringAsDefault
                v = StringAsDefault(v)
            parser.add_argument(
                option_name,
                type=_make_value_names_been_set_injection(
                    k, _get_argument_type_by_value(v)),
                default=v,
                help=help,
            )

    make_option = lambda name: "--{}-{}".format(action_prefix, name)

    for action in inject_actions:
        if action == "list":
            parser.add_argument(
                make_option("list"),
                action="store",
                default=None,
                const="yaml",
                nargs="?",
                choices=["detail", "yaml", "json"],
                help=("List all available hyperparameters. If `{} detail` is"
                      " specified, a verbose table will be print").format(
                          make_option("list")),
            )
        elif action == "detail":
            parser.add_argument(
                make_option("detail"),
                action="store_true",
                help="Shorthand for --hp-list detail",
            )
        elif action == "save":
            parser.add_argument(
                make_option("save"),
                help=("Save hyperparameters to a file. The hyperparameters"
                      " are saved after processing of all other options"),
            )

        elif action == "load":
            parser.add_argument(
                make_option("load"),
                help=("Load hyperparameters from a file. The hyperparameters"
                      " are loaded before any other options are processed"),
            )

    if "load" in inject_actions or "save" in inject_actions:
        parser.add_argument(
            make_option("serial-format"),
            default=serial_format,
            choices=config.HP_SERIAL_FORMAT_CHOICES,
            help=("Format of the saved config file. Defaults to {}."
                  " It can be set to override auto file type deduction."
                  ).format(serial_format),
        )

    if inject_actions:
        parser.add_argument(
            make_option("exit"),
            action="store_true",
            help="process all hpargparse actions and quit",
        )

    def __hpargparse_value_names_been_set(self):
        return value_names_been_set

    parser.__hpargparse_value_names_been_set = MethodType(
        __hpargparse_value_names_been_set, parser)

    return parser
示例#18
0
        switch = 1

    elif event.type() == QEvent.MouseButtonPress and switch == 1:

        draw_line(event)
        self.update()  # requests a paint event
        switch = 0

    elif event.type(
    ) == QEvent.Paint:  # (you're only allowed to draw here (in a paint event) ?)
        painter.begin(self)  # use second painter to draw image on widget
        painter.drawImage(0, 0, img)
        painter.end()

    return True  # return True to tell that the event is handled completely


def erase():
    img.fill(Qt.white)
    #circles = ()         ############ TODO deleting circle list does not work ############
    w.widget.update()


w.widget.event = MethodType(
    drawing,
    w.widget)  # ersetzt die Funktion, die die Ereignisse behandelt ???
w.eraseButton.clicked.connect(erase)

w.show()
sys.exit(app.exec_())
示例#19
0
    def initiate_template(self):
        module = super(Simulator, self).initiate(plg_type="simulator")

        # Replacing auxiliary functions:
        if hasattr(module, "simul"):
            self.simul = MethodType(module.simul, self)
示例#20
0
    def __init__(self,
                 circumference,
                 harmonic_list,
                 voltage_list,
                 phi_offset_list,
                 alpha_array,
                 gamma_reference,
                 p_increment=0,
                 phase_lock=True,
                 shrink_transverse=True,
                 shrink_longitudinal=False,
                 D_x=0,
                 D_y=0,
                 charge=None,
                 mass=None,
                 *args,
                 **kwargs):
        """
        The first entry in harmonic_list, voltage_list and
        phi_offset_list defines the parameters for the one
        accelerating Kick object (i.e. the accelerating RF system).

        For several accelerating Kick objects one would have to
        extend this class and settle for the relative phases
        between the Kick objects! (For one accelerating Kick object,
        all the other Kick objects' zero crossings are displaced by
        the negative phase shift induced by the accelerating Kick.)

        The length of the momentum compaction factor array alpha_array
        defines the order of the slippage factor expansion.
        (See the LongitudinalMap class for further details.)

        RFSystems comprises a half the circumference drift,
        then all the kicks by the RF Systems in one location,
        then the remaining half the circumference drift.
        This Verlet algorithm ("leap-frog" featuring O(n_turn^2) as
        opposed to symplectic Euler-Cromer with O(n_turn)) makes
        sure that the longitudinal phase space is read out in
        a symmetric way (otherwise phase space should be tilted
        at the entrance or exit of the cavity / kick location!
        cf. discussions with Christian Carli).

        The boolean parameter shrink_longitudinal determines whether the
        shrinkage ratio \\beta_{n+1} / \\beta_n should be taken
        into account during the second Drift.
        (See the Drift class for further details.)

        The boolean parameter shrink_transverse allows for transverse
        emittance cooling from acceleration.

        Arguments:
        - self.p_increment is the momentum step per turn of the
        synchronous particle, it can be continuously adjusted to
        reflect different slopes in the dipole magnet strength ramp.
        (See the Kick class for further details.)
        - phase_lock == True means all phi_offsets are given w.r.t. the
        fundamental kick, adjusted at set-up time.
        - phase_lock == False means all phi_offsets are absolute.
        In this case take care about all Kick.p_increment attributes --
        highly non-trivial, as all other p_increment functionality
        in RFSystems is broken. So take care, you're on your own! :-)
        - D_x, D_y: horizontal and vertical dispersion. These arguments
          are passed to the Kicks class. Because both kicks are applied
          consecutively, the dispersion will be the same for both kicks and
          it is therefore sufficient to specify only one dispersion.
          The dispersion must match the dispersion of the following transverse
          map. See the docstring of the Kick class for a more detailed
          description.
        """

        self.charge = charge
        self.mass = mass
        self.gamma = gamma_reference

        super(RFSystems, self).__init__(alpha_array, circumference, *args,
                                        **kwargs)

        if not len(harmonic_list) == len(voltage_list) == len(phi_offset_list):
            self.warns("Parameter lists for RFSystems do not have the " +
                       "same length!")

        self._shrinking = shrink_longitudinal
        if not shrink_transverse:
            self.track = self.track_no_transverse_shrinking

        self._kicks = [
            Kick(alpha_array, self.circumference, h, V, dphi, D_x=D_x, D_y=D_y)
            for h, V, dphi in zip(harmonic_list, voltage_list, phi_offset_list)
        ]
        self._elements = ([Drift(alpha_array, 0.5 * self.circumference)] +
                          self._kicks +
                          [Drift(alpha_array, 0.5 * self.circumference)])
        self._accelerating_kick = self._kicks[0]
        self._shrinking_drift = self._elements[-1]

        self.p_increment = p_increment

        if phase_lock:
            self._phaselock(gamma_reference, charge)
        '''Take care of possible memory leakage when accessing with many
        different gamma values without tracking while setting
        RFSystems.p_increment != 0. Many dict entries will be generated!
        '''
        self._rfbuckets = {}

        self._voltages = utils.ListProxy(self._kicks, "voltage")
        self._harmonics = utils.ListProxy(self._kicks, "harmonic")
        self._phi_offsets = utils.ListProxy(self._kicks, "phi_offset")
        # SORRY FOR THE FOLLOWING CODE!
        # any write access to the above ListProxy instances changes
        # Kick parameters and should therefore result in
        # discarding all saved RFBucket instances:
        voltages_setitem = attach_clean_buckets(
            self._voltages._rewritable_setitem, self)
        harmonics_setitem = attach_clean_buckets(
            self._harmonics._rewritable_setitem, self)
        phi_offsets_setitem = attach_clean_buckets(
            self._phi_offsets._rewritable_setitem, self)

        self._voltages._rewritable_setitem = MethodType(
            voltages_setitem, self._voltages)
        self._harmonics._rewritable_setitem = MethodType(
            harmonics_setitem, self._harmonics)
        self._phi_offsets._rewritable_setitem = MethodType(
            phi_offsets_setitem, self._phi_offsets)
示例#21
0
class Student(object):
    pass


s = Student()
s.name = 'wangkai'  #动态给实例绑定一个属性
print(s.name)


def set_age(self, age):
    self.age = age


from types import MethodType
s.set_age = MethodType(set_age, s)  #给实例绑定一个方法
s.set_age(25)  #调用实例方法
print(s.age)

#给一个实例绑定的方法,对另一个实例是不起作用的


#给所有实例绑定方法!
def set_score(self, score):
    self.score = score


Student.set_score = MethodType(set_score, Student)

s2 = Student()
s2.set_score(100)
print(s2.score)
示例#22
0
    def _make_protocol_method(self, protocol):
        """Make a method closure based on a protocol definition.

        This takes a protocol and generates a closure that has the same arity
        as the protocol. The closure is dynamically set as a method on the
        Remote object with the same name as protocol. This makes it possible
        to do:

        Geonotebook._remote.set_center(-74.25, 40.0, 4)

        which will validate the arguments, create a JSONRPC request object,
        generate a Promise and store it in the _promises dict.
        e.g:

        def handle_error(error):
            print "JSONError (%s): %s" % (error['code'], error['message'])

        def handle_reply(result):
            print(result)

        def handle_callback_error(error):
            print "Callback Error: %s" % error[0]

        Geonotebook._remote.set_center(-74.25, 40.0, 4).then(
            handle_reply, handle_error).catch(handle_callback_error)



        :param protocol: a protocol dict
        :returns: a closure that validates RPC arguments and returns a Promise
        :rtype: MethodType

        """
        assert 'required' in protocol, \
            "protocol {} must define required arguments".format(
                protocol['procedure'])
        assert 'optional' in protocol, \
            "protocol {} must define optional arguments".format(
                protocol['procedure'])

        for arg in protocol["required"]:
            assert 'key' in arg, \
                "protocol {} is malformed, argument {} " + \
                "does not have a key".format(
                    protocol['procedure'], arg)

        for arg in protocol["optional"]:
            assert 'key' in arg, \
                "protocol {} is malformed, argument {} " + \
                "does not have a key".format(
                    protocol['procedure'], arg)

        def _protocol_closure(self, *args, **kwargs):
            try:
                self.validate(protocol, *args, **kwargs)
            except Exception as e:
                # TODO: log something here
                raise e

            def make_param(key, value, required=True):
                return {'key': key, 'value': value, 'required': required}
            # Get the parameters
            params = [
                make_param(k['key'], v) for k, v in zip(
                    protocol['required'], args)
            ]
            # Not technically available until ES6
            params.extend([
                make_param(k['key'], kwargs[k['key']], required=False)
                for k in protocol['optional'] if k['key'] in kwargs
            ])

            # Create the message
            msg = json_rpc_request(protocol['procedure'], params)

            # Set up the callback
            self._promises[msg['id']] = Promise()
            self._send_msg(msg)

            # return the callback
            return self._promises[msg['id']]

        return MethodType(_protocol_closure, self)
示例#23
0
    # Send a trace activity if we're talking to the Bot Framework Emulator
    if context.activity.channel_id == "emulator":
        # Create a trace activity that contains the error object
        trace_activity = Activity(
            label="TurnError",
            name="on_turn_error Trace",
            timestamp=datetime.utcnow(),
            type=ActivityTypes.trace,
            value=f"{error}",
            value_type="https://www.botframework.com/schemas/error",
        )
        # Send a trace activity, which will be displayed in Bot Framework Emulator
        await context.send_activity(trace_activity)


ADAPTER.on_turn_error = MethodType(on_error, ADAPTER)

MEMORY = MemoryStorage()
ACTIVITY_LOG = ActivityLog(MEMORY)
# Create the Bot
BOT = MessageReactionBot(ACTIVITY_LOG)

# Listen for incoming requests on /api/messages.s
@APP.route("/api/messages", methods=["POST"])
def messages():
    # Main bot message handler.
    if "application/json" in request.headers["Content-Type"]:
        body = request.json
    else:
        return Response(status=415)
示例#24
0
    def __init__(self, params, **kwargs):
        """
        __init__ function call to initialize variables from the
        parameters for the class instance provided in __main__ and
        add new variables for use in other functions in this class.
        """

        for name, value in kwargs.items():
            if isinstance(value, FunctionType):
                setattr(self, name, MethodType(value, self))
            else:
                setattr(self, name, value)

        self.time_A = np.linspace(-params.timeAMP_A, params.timeAMP_A,
                                  params.timeDIM_A)
        self.time_R = np.linspace(-params.timeAMP_R, params.timeAMP_R,
                                  params.timeDIM_R)

        self.field_A = np.zeros(params.timeDIM_A, dtype=np.complex)
        self.field_R = np.zeros(params.timeDIM_R, dtype=np.complex)

        self.matrix_gamma_pd = np.ascontiguousarray(self.matrix_gamma_pd)

        self.matrix_gamma_dep_ChR2 = np.ascontiguousarray(
            self.matrix_gamma_dep_ChR2)
        self.matrix_gamma_dep_BLUF = np.ascontiguousarray(
            self.matrix_gamma_dep_BLUF)

        self.mu = np.ascontiguousarray(self.mu)
        self.rho_0 = np.ascontiguousarray(params.rho_0)

        self.rho_ChR2 = np.ascontiguousarray(params.rho_0.copy())
        self.rho_BLUF = np.ascontiguousarray(params.rho_0.copy())

        self.energies_ChR2 = np.ascontiguousarray(self.energies_ChR2)
        self.energies_BLUF = np.ascontiguousarray(self.energies_BLUF)

        self.N = len(self.energies_ChR2)

        self.abs_spectra_ChR2 = np.ascontiguousarray(
            np.zeros(len(self.frequency_A_ChR2)))
        self.abs_spectra_BLUF = np.ascontiguousarray(
            np.zeros(len(self.frequency_A_BLUF)))

        self.abs_dist_ChR2 = np.ascontiguousarray(
            np.empty((len(self.prob_ChR2), len(self.frequency_A_ChR2))))
        self.abs_dist_BLUF = np.ascontiguousarray(
            np.empty((len(self.prob_BLUF), len(self.frequency_A_BLUF))))

        self.dyn_rho_A_ChR2 = np.ascontiguousarray(np.zeros(
            (N, params.timeDIM_A)),
                                                   dtype=np.complex)
        self.dyn_rho_A_BLUF = np.ascontiguousarray(np.zeros(
            (N, params.timeDIM_A)),
                                                   dtype=np.complex)

        self.dyn_rho_R_ChR2 = np.ascontiguousarray(np.zeros(
            (N, params.timeDIM_R)),
                                                   dtype=np.complex)
        self.dyn_rho_R_BLUF = np.ascontiguousarray(np.zeros(
            (N, params.timeDIM_R)),
                                                   dtype=np.complex)
示例#25
0
#自己组装一个类
from types import MethodType


class A():
    pass


def say(self):
    print("Saying.....")


class B():
    def say(self):
        print("Saying.....")


#方法1
say(5)
#方法2
A.say = say
a = A()
a.say()
#方法3
b = B()
b.say()
#方法4
a = A()
a.say = MethodType(say, A)
a.say()
示例#26
0
    def __init__(self, win, setup):
        win_size = pygame.display.get_surface().get_size()
        self.win = win
        self.win_width, self.win_height = win_size

        self.active = False
        self.start_pause = False
        self.end_pause = False
        self.quit = False

        self.menu_size = (self.win_width * (1 / 5), self.win_height * (1 / 8), self.win_width * (3 / 5),
                          self.win_height * (6 / 8))
        self.dirtyrect = pygame.Rect(self.menu_size)
        self.pos_x = self.win_width * (1 / 5)
        self.pos_y = self.win_height * (1 / 8)

        self.bar_pos = (self.win_width * (3 / 10), self.win_height * (2 / 8),
                        self.win_width*(4/10), self.win_height * (1 / 32))
#        self.win = pygame.Surface(win_size)

        self.nr_selectables = [1, 1, 1, 1, 1]
        self.selected = [1, 0, 0, 0, 0]
        self.select_pos = [self.win_width * (3 / 10), self.win_height * (2 / 8),
                           self.win_width*(4/10), self.win_height * (1 / 32)]

        self.screen = "pause_menu"

        self.options = {"bgcol": (0, 0, 0)}

        self.font = pygame.font.SysFont('Courier', 16, True)

        but1 = self.Button(self.bar_pos, "Weiter", self.font, (0, 4), self.menu_size)
        but1.fun = MethodType(self.end_pause_fun, but1)
        but2 = self.Button(self.bar_pos, "Optionen", self.font, (1, 4), self.menu_size)
        but2.fun = MethodType(self.options_fun, but2)
        but3 = self.Button(self.bar_pos, "Hilfe", self.font, (2, 4), self.menu_size)
        but3.fun = MethodType(self.help_fun, but3)
        but4 = self.Button(self.bar_pos, "Grafik", self.font, (3, 4), self.menu_size)
        but4.fun = MethodType(self.graphics_fun, but4)
        but5 = self.Button(self.bar_pos, "Beenden", self.font, (4, 4), self.menu_size)
        but5.fun = MethodType(self.quit_fun, but5)

        but10 = self.Button(self.bar_pos, "option 1", self.font, (0, 4), self.menu_size)
        but10.fun = MethodType(self.options1_fun, but10)
        but11 = self.Button(self.bar_pos, "option 2", self.font, (1, 4), self.menu_size)
        but11.fun = MethodType(self.pause_fun, but11)
        but12 = self.Button(self.bar_pos, "option 3", self.font, (2, 4), self.menu_size)
        but12.fun = MethodType(self.pause_fun, but12)
        but13 = self.Button(self.bar_pos, "option 4", self.font, (3, 4), self.menu_size)
        but13.fun = MethodType(self.pause_fun, but13)
        but14 = self.Button(self.bar_pos, "Zurück", self.font, (4, 4), self.menu_size)
        but14.fun = MethodType(self.pause_fun, but14)

        but100 = self.Button(self.bar_pos, "suboption 1", self.font, (0, 6), self.menu_size)
        but100.fun = MethodType(self.options_fun, but100)
        but101 = self.Button(self.bar_pos, "suboption 2", self.font, (1, 6), self.menu_size)
        but101.fun = MethodType(self.options_fun, but101)
        but102 = self.Button(self.bar_pos, "suboption 3", self.font, (2, 6), self.menu_size)
        but102.fun = MethodType(self.options_fun, but102)
        but103 = self.Button(self.bar_pos, "suboption 4", self.font, (3, 6), self.menu_size)
        but103.fun = MethodType(self.options_fun, but103)
        but104 = self.Button(self.bar_pos, "suboption 5", self.font, (4, 6), self.menu_size)
        but104.fun = MethodType(self.options_fun, but104)
        but105 = self.Button(self.bar_pos, "suboption 6", self.font, (5, 6), self.menu_size)
        but105.fun = MethodType(self.options_fun, but105)
        but106 = self.Button(self.bar_pos, "Zurück", self.font, (6, 6), self.menu_size)
        but106.fun = MethodType(self.options_fun, but106)

        but20 = self.Button(self.bar_pos, "Zurück", self.font, (4, 4), self.menu_size)
        but20.fun = MethodType(self.pause_fun, but20)

        sli30 = self.Slider(self.bar_pos, (1, 0, 0), (0, 4), self.menu_size)
        sli30.fun = MethodType(self.pause_fun, sli30)
        sli31 = self.Slider(self.bar_pos, (0, 1, 0), (1, 4), self.menu_size)
        sli31.fun = MethodType(self.pause_fun, sli31)
        sli32 = self.Slider(self.bar_pos, (0, 0, 1), (2, 4), self.menu_size)
        sli32.fun = MethodType(self.pause_fun, sli32)
        dis33 = self.Display(self.bar_pos, (3, 4), self.menu_size)
        but34 = self.Button(self.bar_pos, "Zurück", self.font, (4, 4), self.menu_size)
        but34.fun = MethodType(self.pause_fun, but34)

        but40 = self.Button(self.bar_pos, "Zurück", self.font, (1, 3), self.menu_size)
        but40.fun = MethodType(self.pause_fun, but40)
        but41 = self.Button(self.bar_pos, "Beenden", self.font, (2, 3), self.menu_size)
        but41.fun = MethodType(self.really_quit_fun, but41)

        self.clickables = {"pause_menu": [but1, but2, but3, but4, but5],
                           "options": [but10, but11, but12, but13, but14],
                           "options1": [but100, but101, but102, but103, but104, but105, but106],
                           "help": [0, 0, 0, 0, but20],
                           "graphics": [sli30, sli31, sli32, dis33, but34],
                           "quit": [0, but40, but41, 0]}
示例#27
0
 def _mock_function(self, obj, func):
     """
     Replaces a bounded function in `self.breaker` by another.
     """
     setattr(obj, func.__name__, MethodType(func, self.breaker))
示例#28
0
 def __get__(self,obj,objtype=None):
     """
     This bounding method will be called only when decorating an
     instance method
     """
     return MethodType(self,obj,objtype)
示例#29
0
 def subscribe(self, name, callback):
     from types import MethodType
     if not isinstance(callback, MethodType):
         callback = MethodType(callback, self)
     super().subscribe(name, callback)
示例#30
0
 def make_method(func, instance, type):
     return MethodType(func, instance, type)