3

I'm trying to define a function (initdeque()) that takes a pointer to an instance of the deque class. So this is what I tried:

from ctypes import *
class deque(Structure):
 pass
deque._fields_ = [("left",POINTER(node)),("right",POINTER(node))]
def initdeque(class deque *p):
 p.left=p.right=None

But this code gives a syntax error:

 def initdeque(class deque *p):
 ^
 SyntaxError: invalid syntax

What is the correct syntax?

Shog9
160k36 gold badges237 silver badges242 bronze badges
asked Aug 23, 2011 at 15:05
2
  • what do you want to do with this ? create a deque class implemented in C ? Commented Aug 23, 2011 at 15:19
  • 4
    ctypes is most definitely not the way to learn Python Commented Aug 23, 2011 at 15:23

2 Answers 2

6

There is no way to specify the type of Python variables, so the declaration of initdequeue should just say:

def initdeque(p):
 p.left = p.right = None

Instead of having a random function doing the initialization, you should consider using an initializer:

class deque(Structure):
 _fields_ = [("left",POINTER(node)), ("right",POINTER(node))]
 def __init__(self):
 self.left = self.right = None

Now, to create a new instance, just write

 p = dequeue()
answered Aug 23, 2011 at 15:09
Sign up to request clarification or add additional context in comments.

13 Comments

sir, but does this "p" become an instance of the deque class??
@kiran No. The type of an object is fixed when it's constructed. Python prefers duck typing over static typing.
what's more, fields should be defined in the class rather than outside
@kiran I urge you to reconsider learning Python via ctypes. The result will be poor knowledge of both.
@kiran I speak from experience. I learnt Python with ctypes and am still trying to recover.
|
0

Python (like Matlab) does not have explicit variable type definition. When a variable is created the compiler defines it's type judging from it's content. So (if I am not wrong) you can call the same function with multiple types as parameters and still work. For example

def fun(p):
 return p=p*5

So u can call fun with a string as a parameter and return you a string that contains 5 times the string you sent. Or you can call it with an integer and the function will return you the result of the multiplication

answered Oct 28, 2012 at 14:15

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.