简体   繁体   中英

Having issue accessing a method from another method within a class in Python

I've created a simple class which I'd like to have return a model.

One of the methods is a simple normalizer which I'd like to be able to call from within another block of code. However it's not finding it. Here's what I have:

class MyClass():

    def __init__(self):
        return
  
    def norm(self, train, x):
        return(x - train['mean'] / train['std'])

    def modelCreator(self, norm, df): 
        train = df.sample(frac=0.8, random_state=0)
        test = df.drop(train.index)

        train_stats = train.describe()
        train_stats = train_stats.transpose()

        normed_train = norm(train)
        normed_test = norm(test)

However, when I try to run this, I get the following error:

modelCreator() is missing 1 required positional argument: 'df'

(I was trying to call the modelCreator method directly and passing it a df)

I also tried to remove "norm" from the definition of modelCreator:

def modelCreator(self, df):

But in this case I get this error:

name 'norm' is not defined

Thank you in advance!

You only need df as a parameter to modelCreator() . You then access your norm method via self.norm . Below is your code updated.

class MyClass():

    def __init__(self):
        return

    def norm(self, train, x):
        return(x - train['mean'] / train['std'])

    def modelCreator(self, df): 
        train = df.sample(frac=0.8, random_state=0)
        test = df.drop(train.index)

        train_stats = train.describe()
        train_stats = train_stats.transpose()

        # These lines below are changed from original
        normed = self.norm(train, test)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM