'How to get updated variable in class?
I have the following code:
class MyClass:
some_variable = None
def __init__(self, args):
data = infile.read()
self.some_variable= int.from_bytes(data[0:4], byteorder="big", signed=False)
if __name__ == "__main__":
with open("input_file", "rb") as infile:
MyClass(infile)
print(MyClass.some_variable)
This prints None, how do I do this?
Solution 1:[1]
You need to access an instance of the class not the class itself
if __name__ == "__main__":
with open("input_file", "rb") as infile:
my_class = MyClass(infile)
print(my_class.some_variable)
Solution 2:[2]
def __init__(self, args):
data = infile.read()
self.some_variable= int.from_bytes(data[0:4], byteorder="big", signed=False)
So your self.some_variable is called an "instance's attribute", and you can access it from an instance:
my_instance_of_MyClass = MyClass(infile)
print(my_instance_of_MyClass.some_variable)
I would suggest you to read this to better understand the difference between class variables and instance variables.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Patrick |
| Solution 2 | FLAK-ZOSO |
