Home > Enterprise >  How can I make my functions to be part of Class?
How can I make my functions to be part of Class?

Time:12-27

I want to make Books/Customer/Loan Classes and make all my function to be part of the class, but instead I only make it worse (I think lol).

I know that my code needs a lot of correction (Make the code more readable) but still maybe some Hero here could help and save my day (Make me learn something new along the way)

P.S: I'm learning how to make readable code so be gentle LOL.

Example of Customer Class of my code:

class Customer:
"""
A class that represents the Customer object
"""

def __init__(self, customer_id, customer_name, customer_city, customer_age):
    """
    A function that contains all the relevant information of customers
    :param customer_id: Customer's ID
    :param customer_name: Customer's name
    :param customer_city: Customer's city of living
    :param customer_age: Customer's age'
    """

    self.customer_id = customer_id
    self.customer_name = customer_name
    self.customer_city = customer_city
    self.customer_age = customer_age

def __str__(self):
    return f"{self.customer_id},{self.customer_name},{self.customer_city},{self.customer_age}"

Example of function that I want to make it part of the Customer Class instead of using it as a regular Function:

def add_new_customer(customer_id, customer_name, customer_city, customer_age):
"""
A function that add new customer to the Library
:param customer_id: Customer's ID'
:param customer_name: Customer's name'
:param customer_city: Customer's city'
:param customer_age: Customer's age'
"""
# todo: try different method that can return dict. return customers_library["Customers"].append({"Customer's ID":customer_id,"Customer's Name":customer_name,"Customer's City":customer_city,"Customer's age":customer_age})

new_customer = customers_library["Customers"].append(
    {"Customer's ID": customer_id, "Customer's Name": customer_name, "Customer's City": customer_city,
     "Customer's age": customer_age})

with open('customers_data.pkl', 'wb') as customer_save:
    pickle.dump(customers_library, customer_save)

return new_customer

CodePudding user response:

First of all, add_new_customer shouldn't be part of Customer class. I would rather see it as a method of Library which could contains collection of all customers. But to make it class method you just need to put it inside class, remember about identation and instance of the class (self) as first parameter.

Another hint and good practice is to not duplicate names - instead of customer.customer_name just write customer.name. In add_customer function you already now you adding customer, so it can take just name, city and age.

id is an exception as it would shadow builting id function and it's really common in database so in that one case it's good to have customer_id.

Another hint, you could remove a lot code with dataclasses

class Customer:
"""
A class that represents the Customer object
"""
from dataclasses import dataclass

@dataclass
class Customer
    customer_id: int
    name: str
    city: str
    age: str

And if we go further, there are possibility to put alias on field with dataclass-json or with pydantic, look:

from pydantic import BaseModel, Field

class Customer(BaseModel):
    customer_id: int = Field(alias="Customer's ID")

    class Config:
        allow_population_by_field_name = True

c = Customer(customer_id=10)
print(c.dict(by_alias=True)) # prints {"Customer's ID": 10}

Which will simplify customer adding a lot (actually you can pickle pydantic model directly but it's one more way to go).

  • Related