Correct Way to Write in Python

Sagar Varule punk.sagar at gmail.com
Sat Aug 3 03:09:35 EDT 2013


On Saturday, August 3, 2013 12:17:49 PM UTC+5:30, Peter Otten wrote:
> punk.sagar at gmail.com wrote:
> 
> 
> 
> > Hi All,
> 
> > 
> 
> > Im new to Python. Im coming from C# background and want to learn Python.
> 
> > I was used to do following thing in C# in my previous experiences. I want
> 
> > to know how do I implement below example in Python. How these things are
> 
> > done in Python.
> 
> > [code]
> 
> > public class Bank
> 
> > {
> 
> > 
> 
> > public List<Customer> lstCustomers = new List<Customer>();
> 
> > private string micrcode;
> 
> > 
> 
> > public void Bank()
> 
> > {
> 
> > customer
> 
> > }
> 
> > 
> 
> > }
> 
> > 
> 
> > public class Customer
> 
> > {
> 
> > private srting customername;
> 
> > 
> 
> > public string CustomerName
> 
> > 
> 
> > {
> 
> > get { return customername; }
> 
> > set { customername = value; }
> 
> > }
> 
> > }
> 
> > 
> 
> > main()
> 
> > {
> 
> > Customer objCustomer = new Customer;
> 
> > objCustomer.CustomerName = "XYZ"
> 
> > 
> 
> > Bank objBank = new Bank();
> 
> > objBank.lstCustomer.Add(objCustomer);
> 
> > 
> 
> > }
> 
> > [/code]
> 
> 
> 
> While I don't know C# I doubt that this is good C# code ;)
> 
> Here's a moderately cleaned-up Python version:
> 
> 
> 
> class DuplicateCustomerError(Exception):
> 
>     pass
> 
> 
> 
> class Customer:
> 
>     def __init__(self, name):
> 
>         self.name = name
> 
> 
> 
> class Bank:
> 
>     def __init__(self):
> 
>         self.customers = {}
> 
>     def add_customer(self, name):
> 
>         if name in self.customers:
> 
>             raise DuplicateCustomerError
> 
>         customer = Customer(name)
> 
>         self.customers[name] = customer
> 
>         return customer
> 
> 
> 
> if __name__ == "__main__":
> 
>     bank = Bank()
> 
>     bank.add_customer("XYZ")
> 
> 
> 
> I'm assuming a tiny bank where every customer has a unique name and only one 
> 
> program is running so that you can ignore concurrency issues.

Thanks a lot Peter. I appreciate your Help. You mentioned that C# code above is not good. If you can point me why it is not good, would help me learn new approaches as this type of Code I use to see long back(when i was fresher). There may be better approaches or concepts i am not aware of. If you can point me in that direction it would be gr8.



More information about the Python-list mailing list