Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8373135
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T14:36:16+00:00 2026-06-09T14:36:16+00:00

I’m trying to port something I wrote in PHP into Python, mainly as an

  • 0

I’m trying to port something I wrote in PHP into Python, mainly as an exercise to better learn the language. The code in question is a SWF parser. In PHP, I have all my data structure declared as classes. I’m trying to do the same in Python but there doesn’t seem to be a explicit way to declare a class variable. So I end up with many classes that look like this:

class SWFRGBA(object):
    red = 0
    green = 0
    blue = 0
    alpha = 0

Do Pythoners actually write things like this?

[EDIT]

Let me post some actual code to illustrate the issue. The function below reads the vector shapes in an SWF file. The readUB(), readSB() reads a certain number of bits interpretating them unsigned or signed. Sometimes, the number of bits required for a given field is itself read from the bitstream. Three types of records might appear: straight edge, quadratic curve, or style change. A style change record might move the pen position, change the line style index, change one of the two fill style indices, or replace the style arrays.

protected function readShapeRecords($numFillBits, $numLineBits, $version, &$bytesAvailable) {
    $records = array();
    while($bytesAvailable) {
        if($this->readUB(1, $bytesAvailable)) {
            // edge
            if($this->readUB(1, $bytesAvailable)) {
                // straight
                $line = new SWFStraightEdge;
                $line->numBits = $this->readUB(4, $bytesAvailable) + 2;
                if($this->readUB(1, $bytesAvailable)) {
                    // general line
                    $line->deltaX = $this->readSB($line->numBits, $bytesAvailable);
                    $line->deltaY = $this->readSB($line->numBits, $bytesAvailable);
                } else {
                    if($this->readUB(1, $bytesAvailable)) {
                        // vertical
                        $line->deltaX = 0;
                        $line->deltaY = $this->readSB($line->numBits, $bytesAvailable);
                    } else {
                        // horizontal 
                        $line->deltaX = $this->readSB($line->numBits, $bytesAvailable);
                        $line->deltaY = 0;
                    }
                }
                $records[] = $line;
            } else {
                // curve
                $curve = new SWFQuadraticCurve;
                $curve->numBits = $this->readUB(4, $bytesAvailable) + 2;
                $curve->controlDeltaX = $this->readSB($curve->numBits, $bytesAvailable);
                $curve->controlDeltaY = $this->readSB($curve->numBits, $bytesAvailable);
                $curve->anchorDeltaX = $this->readSB($curve->numBits, $bytesAvailable);
                $curve->anchorDeltaY = $this->readSB($curve->numBits, $bytesAvailable);
                $records[] = $curve;
            }
        } else {
            $flags = $this->readUB(5, $bytesAvailable);
            if(!$flags) {
                break;
            } else {
                // style change
                $change = new SWFStyleChange;
                if($flags & 0x01) {
                    $change->numMoveBits = $this->readSB(5, $bytesAvailable);
                    $change->moveDeltaX = $this->readSB($change->numMoveBits, $bytesAvailable);
                    $change->moveDeltaY = $this->readSB($change->numMoveBits, $bytesAvailable);
                }
                if($flags & 0x02) {
                    $change->fillStyle0 = $this->readUB($numFillBits, $bytesAvailable);
                }
                if($flags & 0x04) {
                    $change->fillStyle1 = $this->readUB($numFillBits, $bytesAvailable);
                }
                if($flags & 0x08) {
                    $change->lineStyle = $this->readUB($numLineBits, $bytesAvailable);
                }
                if($flags & 0x10) {
                    $change->newFillStyles = $this->readFillStyles($version, $bytesAvailable);
                    $change->newLineStyles = $this->readLineStyles($version, $bytesAvailable);
                    $change->numFillBits = $numFillBits = $this->readUB(4, $bytesAvailable);
                    $change->numLineBits = $numLineBits = $this->readUB(4, $bytesAvailable);
                }
                $records[] = $change;
            }
        }
    }
    $this->alignToByte();
    return $records;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T14:36:17+00:00Added an answer on June 9, 2026 at 2:36 pm

    Yes, I’m afraid a class like that would look kind of dumb to anyone who knew Python well.

    A real Pythonista might use a metaclass to parameterize the making of the sort of classes you want. A metaclass is just a class whose instances are other classes. Here’s an example of one that does many of the things I think you want (from your question and comments):

    from copy import copy
    
    class MetaStruct(type):
        def __init__(cls, name, bases, cls_dict):
            try:
                fields = cls_dict['fields']
            except KeyError:
                raise TypeError("No 'fields' attribute defined in class " + `name`)
    
            # field names may be separated by whitespace and/or commas
            fields = fields.replace(',', ' ').split()
            del cls_dict['fields']  # keep out of class instances
    
            if 'default_field_value' not in cls_dict:
                default_field_value = None  # default default field value
            else:
                default_field_value = cls_dict['default_field_value']
                del cls_dict['default_field_value']   # keep out of class instances
    
            super(MetaStruct, cls).__init__(name, bases, cls_dict)
    
            def __init__(self, **kwds):
                """ __init__() for class %s """ % name
                self.__dict__.update(zip(fields, [copy(default_field_value)
                                                      for _ in xrange(len(fields))]))
                self.__dict__.update(**kwds)
    
            def __setattr__(self, field, value):
                """ Prevents new field names from being added after creation. """
                if field in self.__dict__:
                    self.__dict__[field] = value  # avoid recursion!
                else:
                    raise AttributeError('Can not add field %r to instance of %r' %
                                         (field, name))
            # add defined methods to class instance
            setattr(cls, '__init__', __init__)
            setattr(cls, '__setattr__', __setattr__)
    

    With the metaclass defined as shown, you can then use it to declare different classes and then create one or more instances of them. In Python memory is mostly managed for you, so there is no new operator like PHP apparently requires. As a result of that, there are no pointers, so access to class members is generally done through dot notation rather than ->.

    With that said, here’s an example of declaring a struct-like class, creating a couple of separate instances of it, and accessing their members:

    # sample usage
    class SWF_RGBA(object):
        __metaclass__ = MetaStruct
        fields = 'red, green, blue, alpha'
        default_field_value = 0  # otherwise would be None
    
    c1 = SWF_RGBA()
    print vars(c1)  # {'blue': 0, 'alpha': 0, 'green': 0, 'red': 0}
    c2 = SWF_RGBA(red=1, blue=4)
    print vars(c2)  # {'blue': 4, 'green': 0, 'alpha': 0, 'red': 1}
    

    You can assign values to as many or few of the class’s fields as you wish in the constructor call by using keyword arguments, which can be given in any order. Unassigned fields are given a default value of None. Fields may be of any type.

    Any existing field of instances of the class created can be referred to using dot notation:

    print c2.blue  # 4
    c2.green = 3  # assign a new value to existing green attribute
    

    But new fields cannot be added after an instance is created:

    c2.bogus = 42  # AttributeError: Can not add field 'bogus' to instance of 'SWF_RGBA'
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
this is what i have right now Drawing an RSS feed into the php,
I'm trying to create an if statement in PHP that prevents a single post
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I want to count how many characters a certain string has in PHP, but
I would like to count the length of a string with PHP. The string
I am trying to render a haml file in a javascript response like so:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.