2

I am a beginner to python and want to understand the python class modules and class variables.

I just want to assign a class function's return value to the class variable. I tried in different ways, are these valid in python?

Sample code:

class Example():
    def class_member(self):
        dict_1 = {'k1' : 'v1','k2' : 'v2'}
        return dict_1

    class_var = class_member()
    print(class_var)

x_obj =  Example()

Errors:

    class_var = class_member()
TypeError: class_member() takes exactly 1 argument (0 given)

    class_var = class_member(self)
NameError: name 'self' is not defined

    class_var = Example.class_member()
NameError: name 'Example' is not defined
3
  • You should include your class and the full error to get a exhaustive answer. Commented Jul 30, 2018 at 19:03
  • I think what you’re looking for is an __init__ method that will do self.var = self.method(). Commented Jul 30, 2018 at 19:16
  • class_var=x_obj.class_member() ? Commented Jul 30, 2018 at 19:19

2 Answers 2

1

If you need to store variable inside a class, You might need an initialization function __init__ with double underscores on opposite sides. And you will need a self in front of the 'class_var'. Which will mean that the variable has become part of the class. And also you will need a self in front of the 'class_member' function. Which will mean that the function belongs to this class.

class Example:
    def __init__(self):
        self.class_member()

    def class_member(self):
        dict_1 = {'k1' : 'v1','k2' : 'v2'}
        self.class_var = dict_1
e = Example()
print(e.class_var) #prints {'k1': 'v1', 'k2': 'v2'}
Sign up to request clarification or add additional context in comments.

Comments

0

Another way to achieve this is to make dict_1 property of the Example class and then return it in the class_member function.

class Example():
  dict_1 = {'k1' : 'v1','k2' : 'v2'}
  def class_member(self):
    return self.dict_1

example = Example()

print(example.dict_1) # prints {'k1': 'v1', 'k2': 'v2'}
print(example.class_member()) # prints {'k1': 'v1', 'k2': 'v2'}

I would recommend to go through this link and read it in detail.

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.