0

I'm trying to understand how classes and self work. I now have the following code that has one class and functions defined in it.

from typing import Dict, Any


class LearnClasses:
    def checks(self) -> Dict[str, Any]:
        return {
            **self.chk1(),
            **self.chk2(),
            **self.chk3(),
        }

    def chk1(self) -> Dict[str, Any]:

        chk_id = self.chk1.__name__

        return {
            f'{chk_id}': "Is"
        }

    def chk2(self) -> Dict[str, Any]:

        chk_id = self.chk1.__name__

        return {
            f'{chk_id}': "it"
        }

    def chk3(self) -> Dict[str, Any]:

        chk_id = self.chk3.__name__

        return {
            f'{chk_id}': "working?"
        }

Could someone explain how to call the function checks in LearnClass?

I tried LearnClasses.checks() and it didn't work.

1 Answer 1

1

In general, to call normal methods in a class, you need to create an instance of the class. Then you call the method on the instance:

instance = LearnClasses()
instance.checks()

Note that the code you have now doesn't make a whole lot of sense. The usual purpose of a class is to store some data along side methods that operate on it. Your LearnClasses class doesn't have any data to store or operate on, so it's not very useful.

A slightly more illustrative example might be:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def info(self):
        return f"{self.name} is {self.age} years old"

You'd create the instance by calling the class, which invokes the __init__ method to store the data we have for the person. The info method does something useful with that data, producing a string:

joe = Person("Joe", 39)
print(joe.info())              # prints "Joe is 39 years old"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.