質問

I have the following piece of Python:

class CollectorGUI(Gtk.Window):
    def __init__(self, prefill, flags, data_to_return):
        """prefill should be an instance of the Prefill class"""
        self.prefill = prefill
        self.flags = flags
        self.data_to_return = data_to_return
    ......

My question is: (1) how to get rid of the documentation string? I want my code to be self-documenting; (2) how to get rid of these three lines:

self.prefill = prefill
self.flags = flags
self.data_to_return = data_to_return

Is there an abbreviation?

役に立ちましたか?

解決

The Prefill requirement can be documented in the method signature using function annotations:

class CollectorGUI(Gtk.Window):
    def __init__(self, prefill: Prefill, flags, data_to_return):

Annotations are discoverable at runtime, just like the docstring is. Annotations are not enforced (they are meant as a more generic stepping stone for different use cases) but are immediately obvious in the signature.

You can then optionally enforce it explicitly by asserting the type:

assert isinstance(prefill, Prefill), 'prefill must be an instance of Prefill'

As for auto-setting your attributes from the function arguments, that's answered elsewhere: What is the best way to do automatic attribute assignment in Python, and is it a good idea?

他のヒント

While you could use inspect to automatically create attributes from the arguments in the method's signature, it would obfuscate the perfectly readable code you have now. One look at the constructor tells me that the class at least has the attributes prefill, flags, and data_to_return.

Making explicit code implicit is often not a good idea.

But if you insist:

import inspect


class C(object):

  def __init__(self, a, b, c):
      spec = inspect.getargspec(getattr(C, "__init__"))
      for arg in spec.args[1:]:
        setattr(self, arg, locals()[arg])



c = C(1, 2, 3)

print c.a
print c.b
print c.c
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top