Python Best Practices: Pass to Method or Instance Variable [closed] - python

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
In Python, should I be writing my methods like option 1 or option 2 in the code below? Thanks!
from someHardware import someHardware
# Option 1, pass the data into method
class SomeClass:
def getValue( self ):
rawData = someHardware.getData()
return self.calculateValue( rawData )
def calculateValue( self, rawData ):
return ( rawData * 100 ) - 5
# Option 2, save data as instance variable
class SomeClass:
def getValue( self ):
self.rawData = someHardware.getData()
return self.calculateValue()
def calculateValue( self ):
return ( self.rawData * 100 ) - 5

If your method is called calculateValue, definitively give it something to calculate on, that's semantically clearer. Also, that method is public (no _ to mark it as not-API), so it should make sense to call it externally.
Also, if you do that, your calculateValue will be independent from self, making it basically a staticmethod, thus:
class SomeClass:
def getValue( self ):
rawData = someHardware.getData()
return self.calculateValue( rawData )
#staticmethod
def calculateValue( rawData ):
return ( rawData * 100 ) - 5
Will make it clearer.

Related

Create new class with init [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 1 year ago.
Improve this question
I need to create new class by type function.
def create_fk_widget_from_model(model, **kwargs):
to_field = kwargs.pop('to_field', 'id')
rel = ManyToOneRel(None, model, to_field) # type: ignore
return type(
f'{model.__name__}ForeignKeyRawIdWidget',
(ForeignKeyRawIdWidget, ),
{'__init__': ForeignKeyRawIdWidget.__init__(
rel=rel,
admin_site=admin.site)}
)
But there is a problem. I need to change __init__ in new class, how to do it?
You probably want something like:
def create_fk_widget_from_model(model, **kwargs):
to_field = kwargs.pop('to_field', 'id')
rel = ManyToOneRel(None, model, to_field) # type: ignore
def __init__(self):
return ForeignKeyRawIdWidget.__init__(self, rel=rel, admin_site=admin.site)
return type(
f'{model.__name__}ForeignKeyRawIdWidget',
(ForeignKeyRawIdWidget, ),
{'__init__': __init__}
)

Problem with sending variable to another function [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 3 years ago.
Improve this question
Call function what checking file content, size, etc
Call function if file was changed by file size, if file size changed check file content, add changes to list or delete from list
Question how to use variable in other function correctly?
import re
import os
from time import sleep
hosts_file = "hosts.txt"
class Hosts(object):
def __init__(self):
self.hosts_file = hosts_file
def get_file_size(self):
f_size = os.stat(self.hosts_file)
return f_size.st_size
def work_with_hosts_file():
host_file_work = Hosts()
file_size = host_file_work.get_file_size()
return file_size # use this var
def compare_hosts_file_size(): # in this function
host_file_work = Hosts()
file_size_check = host_file_work.get_file_size()
if file_size != file_size_check:
#do stuff
if __name__ == "__main__":
work_with_hosts_file()
get_connection_hosts_info()
while True:
compare_hosts_file_size()
sleep(5.0)
Thank you in advance!
You need to assign the returned value of work_with_hosts_file() to a variable, and then pass that as an argument to compare_hosts_file_size().
import re
import os
from time import sleep
hosts_file = "hosts.txt"
class Hosts(object):
def __init__(self):
self.hosts_file = hosts_file
def get_file_size(self):
f_size = os.stat(self.hosts_file)
return f_size.st_size
def work_with_hosts_file():
host_file_work = Hosts()
file_size = host_file_work.get_file_size()
return file_size # use this var
def compare_hosts_file_size(file_size): # in this function
host_file_work = Hosts()
file_size_check = host_file_work.get_file_size()
if file_size != file_size_check:
#do stuff
if __name__ == "__main__":
size = work_with_hosts_file()
get_connection_hosts_info()
while True:
compare_hosts_file_size(size)
sleep(5.0)

Python Classes and Inheritance [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 8 years ago.
Improve this question
I'm studying Python programming and I'm having difficulty understanding Inheritance. My assignment is to:
Create a Division and Department class.
Create a method named “getList()” which will display a message, “The
dept department has fullTime full-time and partTime part-time
instructors.”
In the “Department” class, assign 12 as value to the fullTime
variable, assign 27 to partTime, and “CIS” to dept. DO NOT create
any method in the “Department” class. and
Create an instance (object) of the “Department” class named
“myDept”. Use this “myDept” object to call the “getList()” method of
“Division” class (through Inheritance).
Here's what I have so far.
class Division():
def __init__(self, dept, fullTime, partTime):
self.dept = dept
self.fullTime = fullTime
self.partTime = partTime
def getList(self):
return "The (0) department has (1) full-time and (2) part-time instructors.".format(self.dept, self.fullTime, self.partTime)
class Department(Division):
myDept = Division(CIS247, 12, 27)
class Division(object):
def __init__(self,dept, fullTime, partTime):
self.fullTime = fullTime
self.partTime = partTime
self.dept=dept
def getList(self):
return "The {0} department has {1} full-time and {2} part-time instructors.".format(self.dept, self.fullTime, self.partTime)
class Department(Division):
pass
myDept = Department("CIS",12,37)
print myDept.getList()
Edited, I missed the "CIS", for string formatting you use {} not ().
Also " DO NOT create any method in the “Department” class." so removed init method.
python classes tutorial

How to call/run a method only one time in python [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 9 years ago.
Improve this question
I want to call/run a method only onetime I tried this but it didn't wotk:
class S ()
_int_(self)
self.xxx = True # i tried with and without
def Packet (event):
if (xxx == True):
self.f(event, xxx)
print xxx
else:
....
def f (event):
print "something"
Do_Somthing
xxx=False
the problem xxx is still true
Best regards
Amer
The whole class's syntax seems wrong to me. You can do something like this
class S:
def __init__(self): # Initializer function for instance members
self.flag = True
def myMethod(self): # Actual method to be called
if self.flag:
....
....
self.flag = False
Change xxx to self.xxx.
The xxx = False creates a new name binding instead of assigning to the field in your object.
Also, there are also some other syntax errors in your code. Is this the actual code you are running? The code you posted shouldn't run.
from itertools import count
class S ()
def __init__(self)
self.xxx = count()
def Packet(self, event):
if next(self.xxx) == 0:
self.f(event)
else:
....
def f(self, event):
print "something"
#Do_Something

very new to python would appreciate [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 9 years ago.
Improve this question
I'm in a python class with a dumb teacher and I havent been able to get anything to work right. Here's a simple program i'm just trying to get to work once i know it doesn't really gget the average.
>>> class two:
def average(a,b):
return int((a+b)/2)
def main():
num = input("Number? ")
x= int(num)
y= average(x+1,x)
print(y)
main()
Number? 5
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
class two:
File "<pyshell#28>", line 9, in two
main()
File "<pyshell#28>", line 7, in main
y= average(x+1,x)
NameError: global name 'average' is not defined
Your error happens because you do not have any global name average in scope when you use it.
You seem to be confused about when and whether to use the class keyword. In your particular example, you don't need it -- both average and main want to be global functions, not class methods.
Try this program instead:
def average(a,b):
return int((a+b)/2)
def main():
num = input("Number? ")
x= int(num)
y= average(x+1,x)
print(y)
main()
Alternatively, if you want to learn about classes:
class two:
def __init__(self, x,y):
self.x = x
self.y = y
def average(self):
return (self.x + self.y)/2
def main():
t = two(7,42)
print(t.average())
main ()
Notice how the declaration of average now includes a self parameter -- this links the call to a particular two object. Notice also how the invocation of average changed: it is now t.average(). In this case, t is the specific object which will be passed as the first parameter of two.average().
def average(a,b):
return int((a+b)/2)
def main():
print 'enter a number'
num = raw_input()
y = average(int(num)+1,int(num))
print y
main()

Categories

Resources