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
There are a number of issues with your class usage here. Error 1 occurs because in your class definition you've stated that class_member() takes in 'self', which is a reference to the current instance of the class, which you have not created. Error 2 occurred because 'self' has been passed into class_member() as if it was a variable. Error 3 is most likely caused by the class definition not being in the file that requires it.
class Example():
def __init__ (self):
self.dict_1 = {'k1' : 'v1','k2' : 'v2'}
def class_member (self):
return self.dict_1
my_object = Example()
class_var = my_object.class_member()
print(class_var)
Be sure to check out the Python docs first next time. https://docs.python.org/3/tutorial/classes.html
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'}
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.
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.