Python - How to access Instance variables? [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
This post was edited and submitted for review 23 days ago.
Improve this question
I recently stumbled upon a problem, How do i access a class's instance variables (aka the variables inside __init__) from outside/inside the file without creating an instance of a class (i.e main = main.foo()).
Example:
class foo:
def __init__(self,name):
self.name = name
class bar:
os.mkdir(foo.name)

you can set the variable as global, and then you will be able to access this variable from everywhere. and also modifying it.
Not sure why you are using nested classes, but:
foo_name = None
class main:
class foo:
def __init__(self,name):
global foo_name
foo_name = self.name = name
class bar:
def __init__(self):
print(foo_name)
main.foo("Jonathan")
main.bar()
Prints out "Jonathan"

Related

Something I don't understand in classes [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 days ago.
Improve this question
I am new and there is some things I don't understand in classes when I am using python .
-The self whit the __init__ method :
I don't really understand what is the meaning of the self when I am defining this
-Methods :
Let's say we have this class :
class Car():
def __init__(self, make, year)
self.make = make
etc.
How can I be referring to something that doesn't even exist
-Functions :
Why do I always have to put self as a parameter in a function
-Another class :
Let's say we have this class :
class Student:
student1 = Student()
student1.name = 'harry'
how could I put the name method if it doesn't even exist too
I am a little bit confused , thank you for answering
I try to watch some YouTube videos but I still can't figure it out

Python - init argument not used in self [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
Improve this question
I came by a code and wanted to get more understanding on when to use such arrangement.
What would be a good scenario of not using __init__'s argument (name) in self?
class ArgumentNotUsedInSelf:
def __init__(self, name: str):
self.type = "user"
user_one = ArgumentNotUsedInSelf("Mike")
print(user_one.type)
Any explanations from architectural (and not only) point of view are most welcome!
Some of the reasons for this can be:
Historical. The class used to use the argument, but it was changed so it's no longer meaningful. The argument was kept for backward compatibility.
Class hierarchy. This may be a child class of a class that uses the argument, but the child overrides the need for it. The argument is required for compatibility with the parent.
Sort of Barmar's historical example... let's say:
ArgumentNotUsedInSelf used to do something with name, but now doesn't.
But name is still used in SubClass, and changing everything could mess up dependent programs.
class ArgumentNotUsedInSelf:
def __init__(self, name: str):
self.type = "user"
class SubClass(ArgumentNotUsedInSelf):
def __init__(self, name):
super(SubClass, self).__init__(name)
self.name = name
x = SubClass('Mike')
print(x.name, x.type)
Output:
Mike user
This would be helpful if you want to store the field "name" of the created object and re-use it later:
class ArgumentNotUsedInSelf:
def __init__(self, name: str):
self.type = "user"
self.name = name
user_one = ArgumentNotUsedInSelf("Mike")
print(user_one.type)
print(user_one.name)

What is the best practice for initializing an instance variable in a class in python? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Below two variants to initialize a class instance variable. What is the best practice for initializing an instance variable in a class in python and why (maybe none of the suggested variants)?
Assumption: variant a because it might be more explicit?
class Example():
def __init__(self, parameter):
# EITHER
# variant a to initialize var_1
self.var_1 = self.initialize_var_1_variant_a(parameter)
# OR
# variant b to initialize var_1
self.initialize_var_1_variant_b(parameter)
# OR something else
# ...
def initialize_var_1_variant_a(self, parameter):
# complex calculations, var_1 = f(parameter)
result_of_complex_calculations = 123
return result_of_complex_calculations
def initialize_var_1_variant_b(self, parameter):
# complex calculations, var_1 = f(parameter)
result_of_complex_calculations = 123
self.var_1 = result_of_complex_calculations
example_instance = Example("some_parameter")
print(example_instance.var_1)
Variant A is the common way to do this. It is very nice to be able to see all of the class members by looking at __init__, instead of having to dive into the other functions (initialize_var_1_variant_b) to find out exactly what attributes are set.
In general, all member attributes that a class will ever have should be initialized in __init__.
To come at it from another angle, initialize_var_1_variant_a should do as little as possible. Calculating the value of var_1 and saving it as a class attribute are two tasks that can be easily broken apart.
It also opens up the possibility of moving initialize_var_1_variant_a outside of the class itself, so it could be re-used by other parts of your program down the line.

How to avoid loading data repetitively in python class [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I invoke a python class in my python file. The python class I invoked will load big data from disk.
# invoke python class
import mypythonclass
def method():
for i in range(100):
mypythonclass.dosomething(params)
# code in mypythonclass
def dosomething(params):
# load data here
# do something
My question is how can I avoid load data repetitively in mypythonclass, thanks.
If the data you are loading will be used by the class instance, you may initialize the data when instantiating the class.
For example:
class MyPythonClass(object):
def __init__(self, data):
self.data = data
def dosomething(self, params):
# use self.data
If possible you should move the class instantiation out of the for loop, so the data is loaded only once. But the example you provided, doesn't have sufficient details, so it is know exactly what you want.
If the data does not change across different instances of the class, you can use class attributes and make dosomething a class method.
class MyPythonClass(object):
data = some_data
#classmethod
def dosomething(cls, params):
# use cls.data
In this case, the data will be available by all the instances of the class.

Python: naming of boolean/flag class attributes [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Coding style question: What is the recommended way of naming flag class attributes, i.e. attributes being True or False. Styles I can think of are:
class MyClass:
def my_method(self):
self.request = False
class MyClass:
def my_method(self):
self.is_request = False
class MyClass:
def my_method(self):
self.request_flag = False
PEP8 does not seem to give a firm recommendation. Is there a canonical way of doing this?
Considering that booleans are mostly used in coditions, the second way seems most appropriate.
o = MyClass()
...
if o.is_request: # very intuitive
# it's a request

Categories

Resources