Expression problem.
Peter Otten
__peter__ at web.de
Wed Oct 6 09:25:57 EDT 2010
Nethirlon . wrote:
> On 6 okt, 11:53, Peter Otten <__pete... at web.de> wrote:
>> Sebastiaan de Haan wrote:
>> > Thank you Chris,
>>
>> > I'll try and find the attribute in the code. That was my conclusion
>> > aswell... The original author must have defined it somewhere...
>>
>> Don't forget to check whether the object's class (or any of its bases)
>> has a __getattr__() or __getattribute__() method.
>>
>> >>> class A(object):
>>
>> ... def __getattr__(self, name):
>> ... return 42
>> ...>>> a = A()
>> >>> a.as
>>
>> File "<stdin>", line 1
>> a.as
>> ^
>> SyntaxError: invalid syntax
>>
>> Note tha you can still access such an attribute using getattr()
>>
>> >>> getattr(a, "as")
>>
>> 42
>>
>> Peter
>
> Thank you Peter,
>
> While searching the document I found the following code:
>
> class Open(dpkt.Packet):
> __hdr__ = (
> ('v', 'B', 4),
> ('as', 'H', 0),
> ('holdtime', 'H', 0),
> ('identifier', 'I', 0),
> ('param_len', 'B', 0)
> )
>
> So, I am new at programming with Python, but doing my best to grasp
> the concept here. From what I am understanding is that the __hdr__ is
> something that the original programmer cameup with for him self. I am
> just curious as to weather the "as" in this piece of code is the one I
> am searching for.
Side note: if the code you have questions about is publicly available it's
always a good idea to give the url. I am assuming that you are referring to
an older version to this beast:
http://code.google.com/p/dpkt/source/browse/trunk/dpkt/bgp.py
Here's where your problem was fixed/adjusted to newer Python versions:
http://code.google.com/p/dpkt/source/detail?r=51
The __hdr__ is indeed an invention of the author of the package, and is feed
to the metaclass* of dpkt.Packet. The metaclass uses it to create __slots__
that are filled dynamically in Packet.__init__().
I recommend that you read the docstring of the Packet class
http://code.google.com/p/dpkt/source/browse/trunk/dpkt/dpkt.py
but only bother about the implementation if you cannot avoid it.
You can always have a second look after you have gained some Python
experience.
Peter
(*) Every class in Python is an instance of its metaclass, i. e. the
relation between metaclass and class is the same as between class and
instance. Custom metaclasses are a powerful feature, but tend to make Python
code harder to grasp.
More information about the Python-list
mailing list