LinuxQuestions.org
Welcome to the most active Linux Forum on the web.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 07-28-2015, 11:25 AM   #1
Nexusfactor
Member
 
Registered: Jan 2015
Distribution: Ubuntu
Posts: 50

Rep: Reputation: Disabled
Writing a Python Class Give C# Equivalent


I'm attempting to learn Python on my own,so, I got a piece of software I had written in C#, and attempted to re-write it in Python. Given the following class I have a few questions:

C#

Code:
sealed class Message
    {
        private int messageID;
        private string message;
        private ConcurrentBag <Employee> messageFor;
        private Person messageFrom;
        private string calltype;
        private string time;
      
       
        public Message(int iden,string message, Person messageFrom, string calltype,string time)
        {
            this.MessageIdentification = iden;
            this.messageFor = new ConcurrentBag<Employee>();
            this.Note = message;
            this.MessageFrom = messageFrom;
            this.CallType = calltype;
            this.MessageTime = time;
        }
    
        public ICollection<Employee> ReturnMessageFor
        {
            get
            {
                return messageFor.ToArray();
            }
    
        }
1. In my class I have a thread-safe collection called messageFor, is there an equivalent in Python? If so, how do I implement it in a python class?

2. I also have a getter for my thread-safe collection? How would I go about doing the same in Python?

3. Does Python have an EqualsTo method to test equality between objects? Or the
equivalent of this in Python?





Code:
  public override bool Equals(object obj)
            {
                if (obj == null)
                {
                    return false;
                }
    
                Message testEquals = obj as Message;
    
                if((System.Object)testEquals == null)
                {
                    return false;
                }
    
                return (this.messageID == testEquals.messageID) && (this.message == testEquals.message) && (this.messageFor == testEquals.messageFor) && (this.messageFrom == testEquals.messageFrom) && (this.calltype == testEquals.calltype);
                
            }
    
            public bool Equals(Message p)
            {
                if ((Object)p == null)
                {
                    return false;
                }
    
                return (this.messageID == p.messageID) && (this.message == p.message) && (this.messageFor == p.messageFor) && (this.messageFrom == p.messageFrom) && (this.calltype == p.calltype);
    
            }
4. Can you make it sealed, so that no one can inherit from it?


What I've got so far:

Code:
class Message:
 

       def __init__(self, messageID, message, callType):
        
          self.messageID = messageID
          self.message = message
          self.callType = callType

Last edited by Nexusfactor; 07-28-2015 at 12:18 PM.
 
Old 07-28-2015, 12:15 PM   #2
rtmistler
Moderator
 
Registered: Mar 2011
Location: USA
Distribution: MINT Debian, Angstrom, SUSE, Ubuntu, Debian
Posts: 9,882
Blog Entries: 13

Rep: Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930
Quote:
Originally Posted by Nexusfactor View Post
]I'm trying to learn Python on my own, so I got a copy of class I'd written in C# and attempt to write it in Python. I've got two questions:

1. How would you write this C# Class in python? My problem is when it comes to the thread-safe collection messageFor. Does Python have thread-safe collections? If so, how would you implement it as shown above?

2. Does Python have an equalsTo method to test for equality between Objects?
You're starting out with a very involved example. Instead first write something small in Python and grow the concepts to include much of what is represented within your example class. Or you can submit what you have to the python interpreter program you have and see where it complains and then correct the syntax piece by piece. My style here would be to start small and grow my class definition until I got an equivalent. This way whatever concepts needed to be re-designed, I learned them as I went along.

Most persons here will offer various suggestions, but the overall intent is that you make an attempt first rather than copy in a bunch of code an ask people to write an equivalent for you.
 
Old 07-28-2015, 01:01 PM   #3
dugan
LQ Guru
 
Registered: Nov 2003
Location: Canada
Distribution: distro hopper
Posts: 11,225

Rep: Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320
Here it is, along with some test code.

To match the following:

Code:
namespace Crystal_Message
Simply put the code in a module named "Crystal_Message.py".

The only method that needed the C# container's thread safety was addEmployee. I added locking to that method, and made the method itself thread-safe.

You will also note the overriding of the __eq__ method (equals operator) and the __hash__ method (GetHashCode in C#).

Code:
from cStringIO import StringIO
from threading import Lock

mutex = Lock()


def main():
    # Some test code to make sure it works.
    message1 = Message(1, "message", "Id", "calltype", "time")

    print "message1: ", str(message1)
    print "hash(message1)", hash(message1)

    message2 = Message(1, "message", "Id", "calltype", "time")
    print "hash(message2)", hash(message2)
    print "message1 == message2:", message1 == message2

    message2.addEmployee("Employee1")
    message2.addEmployee("Employee2")
    print "message2: ", str(message2)


class Message(object):
    def __init__(self, iden, message, messageFrom, calltype, time):
        self.MessageID = iden
        self.messageFor = []
        self.Note = message
        self.MessageFrom = messageFrom
        self.CallType = calltype
        self.MessageTime = time

    @property
    def ReturnMessageFor(self):
        return self.messageFor

    @property
    def MessageTime(self):
        return self.time

    @MessageTime.setter
    def MessageTime(self, value):

        if not value:
            raise ValueError("Need to Provide Time")

        self.time = value

    @property
    def MessageIdentification(self):
        return self.MessageID

    @MessageIdentification.setter
    def MessageIdentification(self, value):

        if value == 0:
            raise ValueError("Must have Message ID")

        self.MessageID = value

    @property
    def Note(self):
        return self.message

    @Note.setter
    def Note(self, value):
        if not value:
            raise ValueError("Must Have a Message")

        self.message = value

    # I removed the MessageFrom property, as it has no value. It's just an attribute now.

    @property
    def CallType(self):
        return self.calltype

    @CallType.setter
    def CallType(self, value):
        if not value:
            raise ValueError("Please specify call type")
        self.calltype = value

    def addEmployee(self, add):
        mutex.acquire()
        self.messageFor.append(add)
        mutex.release()

    def __str__(self):
        value = "Message: {} From: {} Call Type: {} For: {} Time: {}".format(
            self.message,
            self.MessageFrom,
            self.calltype,
            self.returnMessageFor(),
            self.time
        )
        return value

    def returnMessageFor(self):
        generate = StringIO()
        for view in self.messageFor:
            generate.write(str(view))
            generate.write(" ")
        return generate.getvalue()

    def __eq__(self, other):
        if not isinstance(other, Message):
            return False

        return all([
            self.MessageID == other.MessageID,
            self.message == other.message,
            self.messageFor == other.messageFor,
            self.MessageFrom == other.MessageFrom,
            self.calltype == other.calltype
        ])

    def __hash__(self):
        return hash(self.MessageID) * 33 ^ hash(self.message) * 33 ^ \
            hash(tuple(self.messageFor)) * 33 ^ hash(self.MessageFrom) * 33 ^ \
            hash(self.calltype)


# Let's try the class out.

if __name__ == '__main__':
    main()

Last edited by dugan; 07-28-2015 at 01:15 PM.
 
Old 07-28-2015, 05:45 PM   #4
dugan
LQ Guru
 
Registered: Nov 2003
Location: Canada
Distribution: distro hopper
Posts: 11,225

Rep: Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320
Thanks for trimming your code down to the parts you actually need help with. Unfortunately, my reply was to the full version.

I see you've added this:

Quote:
4. Can you make it sealed, so that no one can inherit from it?
The real answer is no.

A Google search for "python sealed class" got me a way to do it, if you really, really want to, but really, the answer is no. That isn't done in Python. Anyway, if you still want to do it, this will work:

http://stackoverflow.com/a/16564232

I believe I've answered everything. Let me know if there's anything that was missed.

Last edited by dugan; 07-28-2015 at 07:38 PM.
 
Old 07-28-2015, 09:45 PM   #5
sundialsvcs
LQ Guru
 
Registered: Feb 2004
Location: SE Tennessee, USA
Distribution: Gentoo, LFS
Posts: 10,659
Blog Entries: 4

Rep: Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941
Generally speaking, though, the final answer will be: "no."

The C# language is a compiled language that is designed to do things that only such languages do. (For example, if you wanted to write a language interpreter, C# would be a fine language to do it in. I know this because I've done it...)

Python, on the other hand, is designed to be an interpreted environment. While it "supports objects and classes," the scope of its implementation is not designed to be so extensive ... nor would it necessarily be appropriate (or perhaps, even implementable) for it so to be.

As a compiler, C# can generate code to do anything, without affecting itself. When the generated program runs, it's completely free to set up and to maintain any environment it wants. As an interpreter, the Python interpreter is "the actual program that the computer is running," and this doesn't change from Python-run to run, even though the bytecode/source-code being interpreted does.

Last edited by sundialsvcs; 07-29-2015 at 08:58 AM.
 
Old 07-29-2015, 06:12 AM   #6
Nexusfactor
Member
 
Registered: Jan 2015
Distribution: Ubuntu
Posts: 50

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by dugan View Post
Thanks for trimming your code down to the parts you actually need help with. Unfortunately, my reply was to the full version.

I see you've added this:



The real answer is no.

A Google search for "python sealed class" got me a way to do it, if you really, really want to, but really, the answer is no. That isn't done in Python. Anyway, if you still want to do it, this will work:

http://stackoverflow.com/a/16564232

I believe I've answered everything. Let me know if there's anything that was missed.
Many thanks for everything. This is fantastic!
 
Old 07-29-2015, 08:34 AM   #7
Nexusfactor
Member
 
Registered: Jan 2015
Distribution: Ubuntu
Posts: 50

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by dugan View Post
Thanks for trimming your code down to the parts you actually need help with. Unfortunately, my reply was to the full version.

I see you've added this:



The real answer is no.

A Google search for "python sealed class" got me a way to do it, if you really, really want to, but really, the answer is no. That isn't done in Python. Anyway, if you still want to do it, this will work:

http://stackoverflow.com/a/16564232

I believe I've answered everything. Let me know if there's anything that was missed.
I posted this same question on StackOverFlow, however, no one did what you were able to do, again Thanks. However, at the bottom the last comment, says

Quote:
Don't return False from __eq__ because of the rhs being the wrong type: return NotImplemented instead. Think of it as three value logic: 'yes', 'no' or 'I don't know' - and if you don't know, python might be able to ask the other object if it knows
Do you agree, and how would you implement what the poster was talking about?
 
Old 07-29-2015, 09:23 AM   #8
dugan
LQ Guru
 
Registered: Nov 2003
Location: Canada
Distribution: distro hopper
Posts: 11,225

Rep: Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320
Quote:
Originally Posted by Nexusfactor View Post
Do you agree, and how would you implement what the poster was talking about?
I don't agree in this case, because the goal is to do the same thing as your C# code, and your C# code returns False if you're comparing the "wrong type".

If I were to implement that, though:

Code:
def __eq__(self, other):
    if not isinstance(other, Message):
        raise NotImplementedError

    return all([
        self.MessageID == other.MessageID,
        self.message == other.message,
        self.messageFor == other.messageFor,
        self.MessageFrom == other.MessageFrom,
        self.calltype == other.calltype
    ])

Last edited by dugan; 07-29-2015 at 09:25 AM.
 
Old 07-29-2015, 12:01 PM   #9
Nexusfactor
Member
 
Registered: Jan 2015
Distribution: Ubuntu
Posts: 50

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by dugan View Post
I don't agree in this case, because the goal is to do the same thing as your C# code, and your C# code returns False if you're comparing the "wrong type".

If I were to implement that, though:

Code:
def __eq__(self, other):
    if not isinstance(other, Message):
        raise NotImplementedError

    return all([
        self.MessageID == other.MessageID,
        self.message == other.message,
        self.messageFor == other.messageFor,
        self.MessageFrom == other.MessageFrom,
        self.calltype == other.calltype
    ])
Thanks for the code, just for my own understanding, how did you learn Python? School? TextBooks? (If so, what where the titles?) Youtube videos?
 
Old 07-29-2015, 12:04 PM   #10
dugan
LQ Guru
 
Registered: Nov 2003
Location: Canada
Distribution: distro hopper
Posts: 11,225

Rep: Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320Reputation: 5320
This was my learn-Python project:

http://duganchen.ca/project/software...tl-mpd-client/

Learning Python was difficult for me, actually. There was one book that did click with me (I think it was by that guy who chose to disappear from the Internet after writing it), but I can't really recall it right now.

Last edited by dugan; 07-29-2015 at 12:08 PM.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Writing a command (for loop) that would ping a Class C subnet medeiom Linux - Newbie 3 03-17-2012 08:49 AM
[SOLVED] writing to /sys/class/gpio/export sharan013 Linux - Embedded & Single-board computer 5 02-22-2012 11:08 AM
python: writing to a curses window from a class daweefolk Programming 1 03-24-2011 11:24 AM
[SOLVED] Python n00b: promoting a derived class to base class? CoderMan Programming 2 03-11-2010 01:46 PM
Class Arrays in Python rootyard Programming 1 02-13-2004 10:58 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 01:53 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration