Home > Back-end >  Function in classes Python
Function in classes Python

Time:10-03

I'm trying to pass some values to initialize a class:

class User:

    def __init__(self, name, age, weight, height, sex):
        self.name = name
        self.age = age
        self.weight = weight
        self.height = height
        self.sex = sex

This is where I try to use them:

def calories():
    
    if  self.sex == "Man":
        #for Man
        kcal = float((10 * self.weight)   (6.26 * self.height) - (5 * self.age)   5)
    else:    
        #for Wman
        kcal = float(655   (9.6 * self.weight)   (1.8 * self.height) - (4.7 * self.age))

    return round(kcal,2)

I tried self.sex, sex, User.sex, super.sex and every single time I got an error.

     if  super.sex == "Man":
AttributeError: type object 'super' has no attribute 'sex'

The only solution I've found was something like this:

def calories(object):

and to use object.sex, object.age etc. Is the above method correct? Or am I doing something wrong?

CodePudding user response:

What you meant to write was this:

class User:
    def __init__(self, name, age, weight, height, sex):
        self.name = name
        self.age = age
        self.weight = weight
        self.height = height
        self.sex = sex

    def calories(self):
        if  self.sex == "Man":
            kcal = float((10 * self.weight)   (6.26 * self.height) - (5 * self.age)   5)
        else:    
            kcal = float(655   (9.6 * self.weight)   (1.8 * self.height) - (4.7 * self.age))

        return round(kcal,2)

user = User('Jon', 1, 1, 1, 'Man')
print(user.calories())

Note how calories() is defined with self as the first (and only) parameter, which is used to access all the member attributes defined in __init__()

CodePudding user response:

When you have a method on a class in python, the first parameter must be self. Any parameter you provide will act in the same way, which is why when you tried it with object it worked.

class SomeClass:

    def __init__(self, my_input):
        self.some_variable = my_input

    def some_function(self):
        print(self.some_variable)

Note that in your __init__ class you have this self variable, and do not receive the error you saw in your calories() class.

Note also that self is not special in any way, it's just a 'convention' for the first variable of a class method, specifically because it gets 'ignored' when you are calling the method:

 obj = SomeClass("Hello")
 obj.some_function()  # No variable is passed here!

Despite not passing a variable, this still works. The self we defined in the method refers to the object itself, and will be automatically inserted by the interpreter when the method is called.

  • Related