How to Write Python Class

Asked 2 months ago, Updated 2 months ago, 1 views

Let me ask you a question about how to write python class.

I created a class (defined two methods) because I wanted to aggregate the customer's purchase price and rank it based on that amount.Method 1 worked as expected, but Method 2 doesn't know how to write it down.(Is it better not to separate the methods in the first place...?)

*In Method 2, we would like to apply it to the "rev" column of the result returned by Method 1.
(I want to create a new column and substitute the results)

I would appreciate it if you could advise me if you notice anything.
Thank you for your cooperation.

# Class definition
class GetRank:
  # Define initialization method
    def_init__(self, transaction_data, mst_customer):    
        self.transaction_data =transaction_data
        self.mst_customer=mst_customer

    # Method 1: Summarize
    def summary (self):
        summary=self.transaction_data.groupby('cst_no', as_index=False).agg({'rev':'sum'})
        return summary

    # Method 2: Customer Ranked by Amount (rev)
    defrank(self,x):
        if1<=x<=4999:
            return 'low'
        elif 5000<=x<=9999:
            return 'middle'
        elifx<=10000:
            return 'high'

        cat_ord=['low', 'middle', 'high']


# Creating an Instance of a Class
thisY = GetRank(trn_thisY, mst_cst_thisY)

# Run Method 1
s_thisY=thisY.summary()

# Run Method 2
????

python

2022-09-30 11:27

1 Answers

The source code shown in the question is a simple function that returns a string of low, middle, high, or None depending on the value of the parameter.
For example:

result=thisY.rank(1)
print(result)
# low is displayed

If you run Method 1 in question and the result is an integer or floating point number, you will get the result by calling:

result=thisY.rank(s_thisY)
print(result)
# Low, middle, high, or none according to the value of s_thisY appears._thisY.

However, if you pass a string or any object as a parameter, you get an error.
Also, no matter what number you pass as a parameter or how many times you call it, the thisY object has no effect or change.

(I want to create and substitute a new column for the result) Does thisY object mean something that includes the Pandas DataFrame, and you want to increase the column to that object by calling the rank() method?

There is no such action in the current source code.
Also, even if you try to add something like that, it will be difficult to get advice and answers because there is no information on what kind of things, how to process and what kind of results you want to get.
If you want those advice or answers, it's better to ask a new question.


2022-09-30 11:27

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.