[Python] Python Usage of del with OOP and Objects

Discussão em 'Python' iniciado por Stack, Dezembro 7, 2024.

  1. Stack

    Stack Membro Participativo

    Dear StackOverflow community. I have a problem in Python. I created a very basic class named Customer with basic methods to simulate real-life customers. However, I encountered an issue. I defined a class method called remove_customer, and I used the *del *keyword inside it. But I observed that my function does not remove the object belonging to the Customer class. I tried taking out the del keyword and putting outside of class , and I noticed that these two approaches yielded different results. I can't figure out why this happened. Can someone clarify the situation I encountered?

    note: I have consulted my teacher but he replied me it is a bad practice using OOP and del like this way.

    class Customer():
    customer_list=[]
    __slots__=["name","age","gender"]
    def __init__(self,name:str,age:int,gender:int):
    self.name=name
    self.age=age
    self.gender=gender
    Customer.add_customer(self)
    def get_name(self):
    return self.name
    def get_age(self):
    return self.age
    def get_gender(self):
    return self.gender
    @classmethod
    def add_customer(cls,customer):
    cls.customer_list.append(customer)


    if __name__=="__main__":
    customer1=Customer("Jack",28,1)
    customer2=Customer("Julia",27,0)
    for x in Customer.customer_list:
    print(x.name)
    Customer.customer_list.remove(customer1)
    del customer1
    print(customer1)


    class Customer():
    customer_list=[]
    __slots__=["name","age","gender"]
    def __init__(self,name:str,age:int,gender:int):
    self.name=name
    self.age=age
    self.gender=gender
    Customer.add_customer(self)
    def get_name(self):
    return self.name
    def get_age(self):
    return self.age
    def get_gender(self):
    return self.gender
    @classmethod
    def add_customer(cls,customer):
    cls.customer_list.append(customer)
    @classmethod
    def remove_customer(cls,customer):
    cls.customer_list.remove(customer)
    del customer


    if __name__=="__main__":
    customer1=Customer("Jack",28,1)
    customer2=Customer("Julia",27,0)
    for x in Customer.customer_list:
    print(x.name)
    Customer.remove_customer(customer1)
    print(customer1)


    first one yields output :

    NameError: name 'customer1' is not defined. Did you mean: 'customer2'?

    But second one yields different output even doing same thing (I only modified place of del) :

    Jack

    Julia

    <main.Customer object at 0x0000026DD3D76D00>

    Continue reading...

Compartilhe esta Página