Custom Data Structures in Python

I'm new to Python and I need to declare my own data structure, but I'm a bit confused about how to do this. I currently have:

class Particle:

    def __init__(self, mass, position, velocity, force):

        self.mass = mass
        self.position, self.velocity, self.force = position, velocity, force

    def __getitem__(self, mass):
        return self.mass

    def __getitem__(self, position):
        return self.position

    def __getitem__(self, velocity):
        return self.velocity

    def __getitem__(self, force):
        return self.force

This does not work, however, when I try to define an instance of a class using:

 p1 = Particle(mass, position, velocity, force)

Each value ends as (0.0, 0.0) (which is the value of speed and force).

Can someone explain where I'm wrong, all I need from the data structure is to pull the data from it, nothing else. (edit: actually, sorry, I will have to change them a bit later)

thank

+5
source share
5 answers

, , __getitem__ . , , . __getitem__ __setitem__ , , , :

p= Particle(foo)
bar = p[0]

, .

, . , , , __init__, . self:

class Particle:
    def __init__(self, mass, position, velocity, force):
        self.mass = mass
        self.position = position
        self.velocity = velocity
        self.force = force

. , :

mass,pos,vel,f = 0,0,0,0 # just for readability
p = Particle(mass,pos,vel,f)
print p.mass, p.position, p.velocity, p.force

, , , python , p, , Particle, :

in [1]: p
out[1]: <__main__.Particle instance at 0x03E1fE68>

, , , " ", . (, __getitem__), . , .

, , , , :

in [2]: p.mass
out[2]: 0

in [3]: p.mass = 2 
in [4]: p.mass
out[4]: 2

, , __init__ class ( / ). , , . , , , , . , , , .

in [5]: p.newattr ='foobar!'
in [6]: p.newattr
out[6]: 'foobar!'

? ... , , . , , , . , .

+15
class Particle:
    def __init__(self, mass, position, velocity, force):
        self.mass = mass
        self.position = position
        self.velocity = velocity
        self.force = force

particle = Particle(1, 2, 3, 4)
print(particle.mass)  # 1

, , @property:

class Particle:
    def __init__(self, mass, position, velocity, force):
        self.mass = mass
        self.position = position
        self.velocity = velocity
        self.force = force

    @property
    def acceleration(self):
        return self.force / self.mass

particle = Particle(2, 3, 3, 8)
print(particle.acceleration)  # 4.0
+7

, collections.namedtuple - , :

from collections import namedtuple

Particle = namedtuple('Particle', 'mass position velocity force')
p = Particle(1, 2, 3, 4)
print p.velocity
+4

( C-language struct), :

class myContainer(object):
    pass  # Do nothing

myContainerObj = myContainer()
myContainerObj.storedAttrib = 5
print myContainerObj.storedAttrib
0

All Articles