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 have many functions that all share the same parameter. They will be inputting and outputting this parameter many times.
For example:
a = foo
a = fun(a)
a = bar(a)
def fun(a):
...
return a
def bar(a):
...
return a
What is more pro-grammatically correct, passing parameters through a function, or having it be globally accessible for all the functions to work with?
a = foo
fun()
bar()
def fun():
global a
...
def bar():
global a
...
The more localised your variables, the better.
This is virtually an axiom for any programming language.
structs in C (and equivalents in other languages such as FORTRAN) grew up from this realisation, and object orientated programming followed shortly after.
For re-usability of method, passing parameter is better way.
I agree with the other answers but just for the sake of completion, as others have pointed out a class sounds like a good idea here. Consider the following.
class myClass(object):
def __init__(self, foo):
self.a = foo
def fun(self):
# do stuff to self.a
def bar(self):
# do something else to self.a
c = myClass(foo)
c.fun()
c.bar()
Related
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.
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 4 years ago.
Improve this question
If I have an object, and within that object I've defined a variable, which of these methods would be considered 'best' for accessing the variable?
Method One
Using a getter function
class MyClass:
def __init__(self):
self.the_variable = 21 * 2
def get_the_variable(self):
return self.the_variable
if __name__ == "__main__"
a = MyClass()
print(a.get_the_variable())
Method Two
Using the #property decorator
class MyClass:
def __init__(self):
self._the_variable = 21 * 2
#property
def the_variable(self):
return self._the_variable
if __name__ == "__main__"
a = MyClass()
print(a.the_variable)
Method Three
Simply accessing it directly
class MyClass:
def __init__(self):
self.the_variable = 21 * 2
if __name__ == "__main__"
a = MyClass()
print(a.the_variable)
Are any of these methods more pythonic than the others?
Method 3 is the standard pythonic way to start. If you need additional logic, filtering or some other behavior for the attribute you can always go back and add a method for the attribute and use the #property decorator at a later time. That's the beauty of python, start with something simple that works. If you later need finer control over the attribute you can create the property and not have to update/change any of the client code that uses the attribute. The client code will not know the difference between accessing the attribute directly vs calling a method and as a result does not have to change.
This ideology is confirmed via PEP 549
Python's descriptor protocol guides programmers towards elegant API design. If your class supports a data-like member, and you might someday need to run code when changing the member's value, you're encouraged to simply declare it as a simple data member of the class for now. If in the future you do need to run code, you can change it to a "property", and happily the API doesn't change.
I think it's not easy to answer since it's based on the program.
class MyClass:
def __init__(self):
self.the_variable = 21 * 2
def get_the_variable(self):
return self.the_variable
But if you want to pass a class attirubete to some variable, I think it's better to use getter-setter, since it is more readable and understandable. Because you are basically telling I ask this value. For example:
if __name__ == "__main__":
a = MyClass()
modified_variable = a.get_the_variable() * 2
In contrary, if you are just using that class attribute, third option a.the_variable is better.
if a.get_the_variable() == 42:
# do something
else:
# do something
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
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
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
It had always been my dream to use someclass.func instead of someclass.func(). I read about the #decorators. And now I ask:
Which way is better?
Way 1
class Main(object):
def __init__(self):
self.func()
def func(self):
print 'hi'
or...
Way 2
class Main(object):
def __init__(self):
self.func
#property
def func(self):
print 'hi'
EDIT
Here is the code:
http://randomgalaxy.com/stackoverflow/python-property-vs-func/term.py
If func really prints values, then no, making it a property is not the right thing to do. Properties are—as the name suggest—values that are attached to the object. As such, a function with the #property decorator should only return a value and have otherwise no side-effects.
Edit: after reading your actual code DEFINITELY Way 1
Most likely: Way 1
BUT it depends on what you're actually trying to do. This case you presented is way oversimplified.
Using the #property decorator is in my experience either a way to protect a class member (only allowing reads), A way to do some bookkeeping when a variable is set/read, or a way to provide access to a member-like function (ie, just returns a value you request even if it requires some extra computation to get that value). I personally like to use it for lazy evaluation
Properties should be values. Not functions.
Example:
class Foo(object):
def __init__(self, a, b):
self.__a = a
self.__b = b
#property
def a(self):
return self.__a
#property
def b(self):
return self.__b
In this example, values are private and you can't change them.
So it's a bad idea to do something else there? I mean in my script function changes my vars and calls another functions – Vik2015 45 secs ago
It's very bad style. You're not in ruby :)