0

I'm new to python. I've heard that everything is an object when it comes to python even if class or function.

As far as I know, the class object is created when the program starts. So I wonder if there's some function for initializing class variables or doing something.

init function can't do because its parameter is self which's for an instance of the class. I want to access the class itself.

class Example():

    def __init__(self):
# I know that this function is called when an instance of this class is created
        pass


    def __something__(cls):
# Is there some function for initializing class object?
# What I wanna do is I want to initialize class variables or call some functions...
# But __init__ function can't do because its parameter is self.
        pass
2
  • 2
    Just do cls_attr = 'Foo' inside the class definition…!? Commented Nov 4, 2019 at 6:32
  • yes, you are looking for a metaclass Commented Nov 4, 2019 at 6:33

2 Answers 2

3

In Python the class object is created at run time as Python is a Dynamic Language.

So if you want to initiate class variables you could just set them right after class definition

class Cls:
  cls_var = "before"

print(Cls.cls_var)
Cls.cls_var = "after"
print(Cls.cls_var)

this would print "before" and "after"

Sign up to request clarification or add additional context in comments.

Comments

-1

you can operate the class you defined directly.

for example, your class name is Example, you can use buildin method dir to see the class method (dir(Example)), use type to see the class type (type(Example)), __dict__ see the class attributes(Example.__dict__) ...

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.