getting variable from the constructor [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I try to write a program and get a variable from a constructor to a method but I don't know how to do it :( I get an error with p.liczba in the method sprawdz. I would like to have here a number from the user. The same situation is with p.wielokrotnosc. I know that I can write this program easier but I really would like to learn OOP with simple examples like this
class Przyklad:
def __init__(self, liczba):
self.liczba = liczba
def podajSzukana(self):
self.wielokrotnosc = 3
class Dane:
def wczytaj(self):
a = int(input('Podaj mi liczbę '))
p = Przyklad(a)
def sprawdz(self):
if (p.liczba % p.wielokrotnosc == 0):
return true
print ('Witaj w programie szukającym wielokrotność liczby 3 \n')
d = Dane()
d.wczytaj()
d.sprawdz()

The problem is not getting the variable from the constructor of Przyklad. The problem is saving it in Dane. The common procedure is to attach it to instance of Dane:
def wczytaj(self):
a = int(input('Podaj mi liczbę '))
self.p = Przyklad(a)
Then, you'll have self.p available in Dane

This is happening because the variable liczba is contained within the class Przyklad, so when you try to access it in Dane, it is not possible.
You should try having liczba be a global variable (which is dangerous), or having Dane be a descendant of Przyklad (these names though....).

a and p are local variables not members of Dane. You have to use self. (as pointed by jonrsharpe) to be able to access this variable from the class context:
class Dane:
def wczytaj(self):
a = int(input('Podaj mi liczbę '))
self.p = Przyklad(a)
def sprawdz(self):
if (self.p.liczba % self.p.wielokrotnosc == 0):
return true
Another issue is that self.wielokrotnosc do not exists until you call podajSzukana(self) method. One way to fix this is calling that function inside your constructor:
class Przyklad:
def __init__(self, liczba):
self.liczba = liczba
self.podajSzukana() // Call the method here.
def podajSzukana(self):
self.wielokrotnosc = 3

Related

Can't print an object outside a function [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm making a simple program in order to compare the currentdate to another date, and I need to separate the "/" and remove trailing zeros; I made a function for that:
def correctdate(compare, Dayslist, Monthslist):
for day in compare:
if day == "/" or day == "\\":
compare.remove(day)
break
else:
Dayslist.append(day)
for removenum in Dayslist:
#* Removing the numbers from the list
compare.remove(removenum)
for month in compare:
Monthslist.append(month)
#* Joining the numbers into a string
correctdate.DaysLeft = "".join(Dayslist)
correctdate.MonthsLeft = "".join(Monthslist)
#* Stripping leading zeros
correctdate.DaysLeft = correctdate.DaysLeft.lstrip("0")
correctdate.MonthsLeft = correctdate.MonthsLeft.lstrip("0")
return
The code works just fine but i want to save the DaysLeft, Monthsleft to print it/edit it ETC..
so i do this:
correctdate(compare,Dayslist,Monthslist)
print(correctdate.Daysleft)
and i get this:
AttributeError: 'function' object has no attribute 'Daysleft'
There was a typo in printing the object attribute
I wrote:
print(correctdate.Daysleft)
Its supposed to be:
print(correctdate.DaysLeft)
Sorry for the inconvenience
You ve to return it in your function, and outside it get it into variables:
def correctdate(compare, Dayslist, Monthslist):
for day in compare:
if day == "/" or day == "\\":
compare.remove(day)
break
else:
Dayslist.append(day)
for removenum in Dayslist:
#* Removing the numbers from the list
compare.remove(removenum)
for month in compare:
Monthslist.append(month)
#* Joining the numbers into a string
correctdate.DaysLeft = "".join(Dayslist)
correctdate.MonthsLeft = "".join(Monthslist)
#* Stripping leading zeros
correctdate.DaysLeft = correctdate.DaysLeft.lstrip("0")
correctdate.MonthsLeft = correctdate.MonthsLeft.lstrip("0")
return correctdate.DaysLeft,correctdate.MonthsLeft
This for return outside function, now you ve to call function correctly:
DaysLeft,Monthsleft = correctdate(compare,Dayslist,Monthslist)
print(DaysLeft,Monthsleft)
Anyway this code "correctdate.MonthsLeft" looks like you want use class and not only functions, so you should use like that https://www.w3schools.com/python/python_classes.asp
def correctdate(compare, Dayslist, Monthslist):
You declare a function with name correctdate that accepts 3 parameters.
correctdate.DaysLeft = "".join(Dayslist)
correctdate.MonthsLeft = "".join(Monthslist)
Then you try to assign a value to a function, which is not possible because correctdate is not a variable, not an object. You just declared it as a function.
What are you trying to achieve?

How do you print variables outside of a 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 am very new to Python. I am currently using Jupyter Notebook and I need to print the variable "pos_best_g" outside of the following class:
class PSO():
def __init__(self,costFunc,x0,bounds,num_particles,maxiter):
global num_dimensions
num_dimensions=len(x0)
err_best_g=-1 # best error for group
pos_best_g=[] # best position for group
# establish the swarm
swarm=[]
for i in range(0,num_particles):
swarm.append(Particle(x0))
# begin optimization loop
i=0
while i < maxiter:
#print i,err_best_g
# cycle through particles in swarm and evaluate fitness
for j in range(0,num_particles):
swarm[j].evaluate(costFunc)
# determine if current particle is the best (globally)
if swarm[j].err_i < err_best_g or err_best_g == -1:
pos_best_g=list(swarm[j].position_i)
err_best_g=float(swarm[j].err_i)
# cycle through swarm and update velocities and position
for j in range(0,num_particles):
swarm[j].update_velocity(pos_best_g)
swarm[j].update_position(bounds)
i+=1
# print final results
print ('FINAL:')
print (pos_best_g)
print (err_best_g)
initial=[5,5,5,5,5] # initial starting location [x1,x2...]
bounds=[(-10,10),(-10,10),(-10,10),(-10,10),(-10,10)] # input bounds [(x1_min,x1_max),(x2_min,x2_max)...]
PSO(func1,initial,bounds,num_particles=15,maxiter=30)
At the moment I get the following result:
FINAL:
[4.999187204673611, 5.992158863901226, 4.614395966906296, 0.7676323454298957, 8.533876878259441]
0.001554888332705297
However, I don't know how to extract the results as they are all within an In[] cell and not an Out[] cell.
What do I need to do to enable this?
Many thanks
There are 2 ways to do this:
1. return "pos_best_g" variable at the end of "init" function.
define a variable before class and define it as global variable inside the class, then change its value at the end of the init
like:
your_new_variable
class PSO():
def __init__(self,costFunc,x0,bounds,num_particles,maxiter):
global num_dimensions
global your_new_variable
...
print ('FINAL:')
print (pos_best_g)
print (err_best_g)
your_new_variable = pos_best_g
Set the result you want to extract as class attributes
class PSO():
def __init__(self,costFunc,x0,bounds,num_particles,maxiter):
...
# Set class attributes
self.pos_best_g = pos_best_g
self.err_best_g = err_best_g
Then you can access it from the object
pso = PSO(func1,initial,bounds,num_particles=15,maxiter=30)
# print final results
print ('FINAL:')
print (pso.pos_best_g)
print (pso.err_best_g)
I am guessing this is your own defined class, right? You can try adding a getter method and later call this method in Jupyter notebook to store the output results in variables as follows:
Just include these small functions inside your class
def get_pos_best(self):
return self.pos_best_g
def get_err_best(self):
return self.err_best_g
Now, inside your notebook do the following:
object_PSO = PSO(costFunc,x0,bounds,num_particles,maxiter)
list_you_want = object_PSO.get_pos_best()
error_you_want = object_PSO.get_err_best()
Good luck!

Please explain the mistake I am making in the piece of code? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Please refer to the code below:
import pandas as pd
import numpy as np
import math
class ElNinoData(object):
# Your implementation here
# class variables
add = 0
count = 0
average = 0
# class methods
def __init__(self , object):
self.object = object
def get_humidity():
return self.object['humidity']
def conversion():
self.object = self.object.astype({'zon_winds':'float64','mer_winds':'float64','humidity':'float64','air_temp':'float64','s_s_temp':'float64'})
return self.object
def replace_null():
if not math.isnan(self.object['humidity']):
global add
global count
global average
add += pd.to_numeric(self.object['humidity'])
count += 1
average = add / count
else:
self.object['humidity'] = average
return self.object['humidity']
def get_obj_it():
lst = ['bouy','day','latitude','longitude','zon_winds','mer_winds','humidity','air_temp','s_s_temp']
df = pd.read_csv('C:\\Users\\suel.abbasi\\Downloads\\elnino.gz', sep='\s+', header=None)
df.columns = lst
df = df.replace({'.':np.nan})
for i , j in df.iterrows():
yield ElNinoData(j)
def average_humidity():
e_n_generator = get_obj_it()
count = 0;
hum_sum = 0;
for e_n_row in e_n_generator:
e_n_row = e_n_row.conversion()
count += 1
hum_sum += e_n_row.get_humidity()
print("Mean Humidity is '{}' Percent".format(hum_sum/count))
average_humidity()
The code keeps throwing an error, I cant understand the error. I am trying to implement a class to programatically represent the data entries.
The error is below is:
TypeError: conversion() takes 0 positional arguments but 1 was
In your class defined functions, you need to pass self as an argument when defining them. So, instead of def conversions():, try def conversion(self). Do the same with get_humidity() and replace_null().

TypeError: 'bool' object is not callable for calling function [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm having the below code which is really simple, but I just can't figure out why I'm getting the above error. I can't seem to call the function defined above, as it is a boolean object??
def server(jobs):
# master clock jumps to next job
global master
master = jobs[0][0]
jobs = [(1, 2.1),(2, 3.3),(3, 1.1),(5, 0.5),(15, 1.7)]
# master clock
master = 0
# server = true when busy, server = false when idle
server = False
next_arrival = jobs[0][0]
# assuming no future arrivals
next_departure = np.inf
job_list = []
print("master clock: " + str(master) + ", next arrival time: " + str(next_arrival) + ", next departure time: " + str(next_departure) + ", job list: " + str(job_list))
server(jobs)
You shadowed your function name with a bool variable when you wrote server = false. You can't have a function and a variable with the same name in the same scope.
Name that variable or the function something else, because False() doesn't make any sense.
You just need to change the name of the function. Change the function name from server to server_new and it will work.

Calling the functions which are already in the callstack [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I wanted to do something like the following. It is an Euclid's algorithm.
1. Why is it not working when I wanted to call the function which is already in the call stack?
2. How can I make it work?
import sys
def __block_1__():
__block_2__()
def __block_2__():
global b,a
b,a=None,None
__block_3__()
def __block_3__():
global b,a
a=int(raw_input())
__block_4__()
def __block_4__():
global b,a
b=int(raw_input())
__block_5__()
def __block_5__():
global b,a
if a==b:
__block_6__()
else:
__block_7__()
def __block_6__():
global b,a
__block_8__()
def __block_8__():
global b,a
sys.exit(0)
def __block_7__():
global b,a
if a<b:
__block_9__()
else:
__block_10__()
def __block_9__():
global b,a
b=b-a
__block_5__
def __block_10__():
global b,a
a=a-b
__block_5__
__block_1__()
That has to be the craziest implementation of Euclid's GCD algorithm I've ever seen! :) And since it uses recursion and subtraction, it's not very efficient. OTOH, I guess it's intriguing, especially since it was auto-generated. (How was it auto-generated, BTW?)
I normally use:
def gcd(a, b):
if a < b:
a, b = b, a
while b > 0:
a, b = b, a%b
return a
In Python, we try to avoid using globals, but I guess we can forgive your auto-generator for that sin. Note that you only need the global statement when you want to modify a global variable, it's not required merely to read a global.
Apart from the missing parentheses in the call to block_5 that BrenBarn mentioned, your program doesn't have any kind of output statement, so once it calculates the gcd it doesn't actually do anything with it. :)
Also note that if either of the args are <= 0 then the recursion stack blows up.
Anyway, I decided to clean your code up & get rid of the redundant blocks, on the off-chance that others might like to trace through the algorithm to see why it works.
#! /usr/bin/env python
''' Calculate the gcd of two positive integers
Uses a recursive state machine implemetation of the naive form
of Euclid's algorithm.
From http://stackoverflow.com/questions/25928184/calling-the-functions-which-are-already-in-the-callstack
Modified by PM 2Ring 2014.09.19
'''
def block3():
global a
a = int(raw_input('a: '))
block4()
def block4():
global b
b = int(raw_input('b: '))
block5()
def block5():
if a == b:
block8()
else:
block7()
def block7():
if a < b:
block9()
else:
block10()
def block8():
print a
exit()
def block9():
global b
b -= a
block5()
def block10():
global a
a -= b
block5()
if __name__ == '__main__':
block3()
I think you'll agree that my version's a bit more readable. :)

Categories