Correct Way to Write in Python
Peter Otten
__peter__ at web.de
Sat Aug 3 02:47:49 EDT 2013
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.
More information about the Python-list
mailing list