How do I declare a variable as a file in python? [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 6 years ago.
Improve this question
This is incredibly noobish, but here's an example of what I want:
class A:
def __init__(self):
self.m_file = file() # name required
self.m_file = None # readonly attribute error
self.m_file = "" # readonly attribute error
def ButtonPressed(self):
self.m_file = open(tkFileDialog.askopenfilename(), 'r')
None of the attempts in __init__ work. I tried searching for python init variable as file but those keywords brought out a lot of posts not answering the question.

As noted in the comments, the open() function in ButtonPressed method will overwrite anything done in the __init__ call. I would recommend keeping this line
def __init__(self):
self.m_file = None
As this will allow you to check whether the variable is None before attempting to use it somewhere else in the class

You probably want to use the open() method. I don't think that you'd want to do this in your constructor, but open() is what you're looking for.

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

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.

Python a class method and defining a default value (if param is empty) and static method [closed]

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 2 years ago.
Improve this question
I've been debugging fix_keep_int_value_as_string for hours now. I thought the proper way to send along a default value for a param was like this def fix_keep_int_value_as_string(self, s='')
Somehow the def method below is always outputting s as an empty string
Why? And how do I correctly set a default param value (if not passed)
class BaseShirtsSpider(Spider):
# Strip numbers only, be aware! returns string
#staticmethod
def fix_keep_int_value_as_string(self, s=''):
print(s)
s = str(s)
print(s)
s = re.sub('[^0-9\-]','',s)
print(s)
return s
class ChildBaseSpider(BaseShirtsSpider):
print(self.fix_keep_int_value_as_string(4))
print(self.fix_keep_int_value_as_string("4"))
There are a couple of issues here:
Static method do not need a self argument. Currently you are trying to pass '4' into the self variable of fix_keep_int_value_as_string rather than the s variable.
The self variable in ChildBaseSpider does not exist until the class has been initialised (i.e. after __init__ method has been called).
Assuming the Spider class does not take any arguments, the following will work:
class BaseShirtsSpider(Spider):
# Strip numbers only, be aware! returns string
#staticmethod
def fix_keep_int_value_as_string(s=''):
print(s)
s = str(s)
print(s)
s = re.sub('[^0-9\-]', '', s)
print(s)
return s
class ChildBaseSpider(BaseShirtsSpider):
def __init__(self):
print(self.fix_keep_int_value_as_string(4))
print(self.fix_keep_int_value_as_string("4"))
ChildBaseSpider()

python singleton vs classmethod [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 5 years ago.
Improve this question
I want to create a service class that just has one instance, so should I make that class a singleton, or should I make the methods as classmethods?
class PromoService():
#classmethod
def create_promo(cls, promotion):
#do stuff
return promo
class DiscountPromoService(PromoService):
#classmethod
def create_promo(cls, promo, discount):
promo = super(DiscountPromoService, cls).create_promo(promo)
promo.discount = discount
promo.save()
return promo
The reason I don't want to create it as a module is because I would need to subclass my service. What is the most pythonic way to do this, the above-mentioned way or to make a singleton class?
Short answer: In my opinion it would work.
BUT, In pure pattern's sense, I have been wrestling with this question for a while:
Do python class methods and class attributes essentially behave like a Singleton?
All instances of that class have no bearing on them
Only class itself have access to them
There is always one of them
Yes, pure Singleton Pattern comparison would fail plain and simple but surely its not far off?
Wouldn't call myself a python expert, so happy to know views on this be corrected on my assumptions.
If you want a singleton, go with a singleton. The pattern referenced here works well. You would simply need to do something like:
class PromoService():
__metaclass__ = Singleton

How to stop a class halfway, to run the next class, and how to do so? [closed]

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 7 years ago.
Improve this question
I searched on the internet and couldn't find a solution. Please help.
Let's say...
class A(self):
def __init__ (self):
"""one chunk of code here"""
if (condition met):
print 'access granted'
"""I want to stop the code here and ask it to run class B, instead of just one method from class B"""
else:
print 'Stop process'
break
class B(self):
def __init__ (self):
"""one more chunk of codes here"""
Is this possible? (pardon my mess of codes)
Your if condition code will run only once when you run that script. Whenever you create an instance of a class, only __init__ function is run. As interjay mentioned, you don't run a class, you run functions.

Categories

Resources