How to access variable from other function in python - python-3.x

I am working on one project and wanted to implement it in OOP. So for that I have craeted one class Person having 2 different methods funcA which returns fullname and funcB which takes varible from funcA and return age.
Now my question is how can i use var2 from function funcA into the funcB.
class Person:
def __init__(self, name):
self.name = name
def funcA(self):
var1 = self.name + "Satav"
var2 = 22
return(var1)
def funcB(self):
return("my age is " + var2)
dc = Person("Mayur")
#first wanted to run funcA
fullname = dc.funcA()
print(fullname)
#then wanted to run funcB
age = funcB()
print(age)
I tried many available solution but got confused. Please apologies for this silly question
I am working on one complex project and because of that it not possible to add entire code here. and that's why i use this dummy scenario

An answer to the edit is to change funcB to:
def funcB(self):
A_VAR = self.funcA
return "my age is " + A_VAR

It would make more sense to make var2 be age and be one of the attributes of the class, that way you could access it in any method that has self in it.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def funcA(self):
var1 = self.name + "Satav"
#since you were only returning var1, var2 was doing nothing here
return(var1)
def funcB(self):
return("my age is " + self.age)
dc = Person("Mayur", 22)
#first wanted to run funcA
fullname = dc.funcA()
print(fullname)
#then wanted to run funcB
age = funcB()
print(age)

After return(var1) in funcA(), put global var2

class Person:
def __init__(self, name):
self.name = name
def funcA(self):
var1 = self.name + "Satav"
self.var2 = 22
return(var1)
def funcB(self):
return("my age is " + str(self.var2))
dc = Person("Mayur")
#first wanted to run funcA
fullname = dc.funcA()
print(fullname)
#then wanted to run funcB
age = dc.funcB()
print(age)
It would be best to set var2 as a local variable of the class instead of one function, as you are calling var2 in another function in another scope. But this here can work.

You can use as follows
def Person(name, age=None):
print('name: {}'.format(name))
if(age is not None):
print('age: {}'.format(age))
else:
print('age: not informed')
And call the function this way
Person('Mayur', 22)
The result
name: Mayur
age: 22
If you call the aged function, this way
Person('Joe')
As defined in the function if you do not enter the age, the function returns
name: Joe
age: not informed

Here try this code-
class Person:
def __init__(self, name):
self.name = name
self.var1 = ''
self.var2 = 0
def funcA(self):
self.var1 = self.name + " Satav"
self.var2 = 22
return(self.var1)
def funcB(self):
return(f"my age is {self.var2}")
dc = Person("Mayur")
#first wanted to run funcA
fullname = dc.funcA()
print(fullname)
#then wanted to run funcB
age = dc.funcB()
print(age)
First of all i have defined the variables in the init menthod so they can be accessed.
And second of all i used f-string to format 'funtB'.
Last of all i fixed some errors in your code.
Cheers!
I Hope the following code helps you further
I have defined the funcB outside of the class. Two values cannot be returned to functA so i have printed them out
def funcB(value):
print(f"my age is {value}")
class Person:
def __init__(self, name):
self.name = name
self.var1 = ''
self.var2 = 0
def funcA(self):
fullname = self.name + " Satav"
print(fullname)
funcB(self.var2)
dc = Person("Mayur")
#first wanted to run funcA
fullname = dc.funcA()

Related

Pyhton3 Code,Class and Methods , why does the method won't return value , though it the code look ok without any problem

i try to build this code see below for the objective and advise why the method "sleep" won't return the value of self.name and the string afterwards if the cat is sleeping.. , the result only gives the second method jumpy.
# Objective:create a class cat with the following attributes:
# name , age , sex
# with the following methods: sleep :
# run only if attribute name is passed
# jumpy : if run function , sex needs to be male
class Cat:
def __init__(self, name='', age='', sex=''):
self.name = name
self.age = age
self.sex = sex
def sleep(self):
if self.name != None:
return f'{self.name} if sleeping, leave him alone!'
def jumpy(self):
if self.sex == "male":
print("the cat jumping like a maniac!!")
else:
print("this cat is lazy Garfield!!")
Mycat = Cat('miki', 5, 'female')
Mycat.sleep()
Mycat.jumpy()
this cat is lazy garfield!!

How to remove an object from list by a value

My problem is that I created a list of students with name and number. The task is now to remove a student by his number. My problem is that my code doesn't work.
Another problem is that it always shows the memory address instead of the value of the object.
Thanks in advance
class Student:
def __init__(self, name, number):
self.name = name
self.number = number
from .student import Student
class Course:
def __init__(self, name, code, credit, student_limit):
self.name = name
self.code = code
self.credit = credit
self.student_limit = student_limit
students = []
def add_student(self, new_student):
self.student = new_student
self.students.append(new_student)
print("Student added" +str(self.students))
def remove_student_by_number(self, student_number):
self.student_number = student_number
if student_number in self.students: self.students.remove(student_number)
print("Student removed" + str(self.students))
from .course import Course
class Department:
def __init__(self, name, code):
self.name = name
self.code = code
courses = []
def add_course(self, course):
self.course = course
self.courses.append(course)
print("Course added" +str(self.courses))
from python import *
def main():
alice = Student("Alice", 1336)
bob = Student("Bob", 1337)
math_dept = Department("Mathematics and Applied Mathematics", "MAM")
math_course = Course("Mathematics 1000", "MAM1000W", 1, 10)
math_dept.add_course(math_course)
math_course.add_student(bob)
math_course.add_student(alice)
math_course.remove_student_by_number(alice.number)
if __name__ == "__main__":
main()
self.students is a list of Student instance so it will print the instance's memory address if the method __str__ is not implemented (see here for example). You should try to print each property like student.name or student.number explicitly.
Anyway you are trying to find student_number in list of Student so of course it will never run the remove line. Instead use if student_number in [student.number for student in self.students] which is looking up the student's number list, not the student list itself. However in this case, you also want to remove the student with the student_number as the input so you may need to use a loop like this:
def remove_student_by_number(self, student_number):
for student in self.students:
if student.number == student_number:
print("Student removed" + str(student.name))
self.students.remove(student)
break

I am not able to print the value by object of the class input taken by the user

print(xyz.age) #not able to print this
class abc:
def __init__(self):
pass
#classmethod
def getinput(self):
self.name = input("enter your name")
self.age= input("enter your age")
self.gender = input("enter your gender")
self.address = input("enter your address")
print( 'your name is {} and age is {} your are {} and you live at {}'.format(self.name,self.age,self.gender,self.address))
xyz = abc.getinput()
print(xyz.age) #not able to print this
You did not instantiate your class correctly you are just calling one of its methods.
Try this...
xyz = abc()
xyz.getinput()
print('Age', xyz.age)
Two things,
1) xyz is not a instance of your class, it is just storing whatever you are returning from getinput(In your case, you are returning None).
2) For accessing variables of abc class, you need to create instance like
xyz = abc(). then you can access the attributes of class through xyz instance.

Python - passing class instantiation to a function

I need to pass the class instantiation to a function.
This is what i wrote so far:
def func(dog):
print(dog.get_name)
def main():
new_dog = dog(name, age, weight)
func(new_dog)
but when i try to execute it i get the following error message:
<bound method animal.get_name of <classes.dog object at 0x7f9611002b70>
Basically i have a class file with the following classes:
animal - Mother class(it include the name getter)
dog - Child class of animal
cat - Child class of animal
What i'm doing wrong?
--EDIT--
Structure of the classes:
class animal:
# public vars
name = ""
age = 0
weight = 0.00
animal_type = ""
# public constructor
def __chars(self):
print("His name is: " + self.name)
print("He is: " + str(self.age) + " y.o.")
print("His weight: " + str(self.weight) + " Kg")
def __init__(self, name, age, weight, animal_type):
self.name = name
self.age = age
self.weight = weight
self.animal_type = animal_type
print("A new animal has been created!")
self.__chars()
# public methods
def eat(self):
print("The animal eat!")
def drink(self):
print("The animal drink!")
def play(self):
print("The animal plays!")
def get_name(self):
return self.name
# public destructor
def __del__(self):
print('\n' + self.name + "has died :(")
# Child classes
class dog(animal):
__dlevel = None # dangerous level, it can be 0, 1 or more, it's private
# private methods
def set_dlevel(self, dlevel):
self.__dlevel = dlevel
print("Dangerous level set!")
def get_dlevel(self):
# CHeck if the level is define
if not self.__dlevel:
print("Dog dangerous level not found")
sys.exit(1)
# if is equal or more than 1 is dangerous
if int(self.__dlevel) >= 1:
print("The dog is dangerous, be careful while playing with him!")
# otherwise it's a quiet dog
elif int(self.__dlevel) <= 0:
print("The dog isn't dangerous")
I figured out the real problem: i was printing the function, not calling it.
So instead i've used
def func(animal):
print(animal.get_name())
def main():
new_dog = dog("max", 14, 11, "dog")
func(new_dog)

How to create addPlayer() method. (Python 3)

I'm currently working on an OOP project in my CSI class in which I have to create various sports team and athlete objects as well as a method addPlayer() for adding the athletes to a roster. This is what I have so far.
class Athlete:
def __init__(self, name, number):
self.name = name
self.number = number
def __str__(self):
return "Athlete(" + self.name + ", " + self.number + ")"
def name(self):
return self.name
def number(self):
return self.number
from Athlete import *
class SportsTeam:
roster = []
def __init__(self, city, name, colors):
self.city = city
self.name = name
self.colors = colors
SportsTeam.roster = roster
def __str__(self):
return "SportsTeam(" + self.city + ", " + self.name + \
", " + str(self.colors) + ", " + ")"
def getcity(self):
return self.city
def getname(self):
return self.name
def getcolors(self):
return self.colors
def getRoster(self):
return SportsTeam.roster
def printRoster(self):
for player in roster:
print("Current Team Roster: " + str(SportsTeam.roster))
def addPlayer(self, player):
SportsTeam.roster.append(player)
return SportsTeam.roster
The thing is when I try to use the addPlayer() method I created, I get an error message telling me that list has no attribute. Not sure what needs to be added to fix this.
P.S I have only been programming for a couple of months, so I apologize if the solution is obvious
When you are dealing with classes, you have your instance variables (like self.city = city) and your class variables (like roster = []).
Instance variables are tied to an instance of the class. So if you create 2 SportsTeam objects, they each have their own city.
Class variables are a little different. They are not tied to an instance of the class; meaning, no matter how many SportsTeam objects you create, there will only be one roster variable.
To me, roster being a class variable seems a bit odd because each SportsTeam should have its own roster. However, if you are required to use class variables for you CSI class, maybe you could keep a list of all_teams and/or all_players.
Taking this into consideration:
class SportsTeam:
all_teams = []
all_players = []
def __init__(self, city, name, colors):
self.city = city
self.name = name
self.colors = colors
self.roster = []
SportsTeam.all_teams.append(self)
def __str__(self):
return "SportsTeam(" + self.city + ", " + self.name + ", " + str(self.colors) + ")"
def getCity(self):
return self.city
def getName(self):
return self.name
def getColors(self):
return self.colors
def getRoster(self):
return self.roster
def printRoster(self):
# the for loop was unnecessary
print("Current Team Roster:", str(self.roster))
def addPlayer(self, player):
SportsTeam.all_players.append(player)
self.roster.append(player)
return self.roster
If you would like to keep roster as a class variable, leave a comment and I can help you adjust the code to accommodate for this.

Resources