I am not able to print the value by object of the class input taken by the user - python-3.x

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.

Related

How to access variable from other function in python

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()

how to access to data from a class which is stored in another class in python?

This is my code. I got a problem when i want to print the information inside the class 'pokemon'
class trainer(object):
def __init__(self, name, pokemons = [], money = 0):
self.name = name
self.pokemons = pokemons
self.money = money
this is my first class which has every pokemon per trainer
class pokemon(object):
def __init__(self, name, attribute, attacks = {}, health = '==========='):
self.name = name
self.attribute = attribute
self.health = health
self.attacks = attacks
The other class where I take the pokemon to import to the other class
class fight():
def __init__(self, fighter1, fighter2):
self.fighter1 = fighter1
self.fighter2 = fighter2
def fighting(self):
if len(Trainer1.pokemons) >= 1 and len(Trainer2.pokemons) >= 1:
print('{} wanna fight against {}'.format(Trainer1.name, Trainer2.name))
keepgoing = True
print('{} got this Pokemons: '.format(Trainer1.name))
i = 0
for i in Trainer1.pokemons:
print(i)
#while (keepgoing):
else:
print('You gotta have pokemons to fight')
return False
I thought that creating a class named fight for getting in battle would be the most wise idea but I'd like to know another method to do it
Pokemon1 = pokemon('Charizard', 'Fire', attacks={'1':'ball fire', '2':'cut', '3':'fire blast', '4':'mega kick'})
Pokemon2 = pokemon('Charmander', 'fire', attacks={'1':'blast', '2':'scratch', '3':'heat', '4':'tear'})
Trainer1 = trainer('Santiago', pokemons=[Pokemon1, Pokemon2])
Pokemon3 = pokemon('Charizard', 'Fire', attacks={'1':'ball fire', '2':'cut', '3':'fire blast', '4':'mega kick'})
Pokemon4 = pokemon('Charmander', 'fire', attacks={'1':'blast', '2':'scratch', '3':'heat', '4':'tear'})
Trainer2 = trainer('Alejandra', pokemons=[Pokemon3, Pokemon4])
Okay my problem is in the class fight. when i want to print the names of the pokemons i get the following message:
Santiago got this Pokemons:
<__main__.pokemon object at 0x000002AAD9B64D00>
<__main__.pokemon object at 0x000002AAD9B92DF0>
i know that the pokemon class has various instances, but how can i access to them?
To make your life easier, I recommend that you implement the __str__ dunder method on pokemon. This will resolve the issue that you are seeing right now, and make future prints of pokemon much easier.
That would look something like this:
class pokemon(object):
def __init__(self, name, attribute, attacks = {}, health = '==========='):
self.name = name
self.attribute = attribute
self.health = health
self.attacks = attacks
def __str__(self):
return "Pokemon: %s (Health: %11s)" % (self.name, self.health)
When you print the 'Charmander' pokemon, it'll look something like this:
Pokemon: Charmander (Health: ===========)
Of course, you can change the return of the __str__ to return whatever you want out of the pokemon.

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

How to make example class object using outside function and acces it from outside. Python3.6

I have a problem or I just do not understand something at all.
I would like to make couple examples objects using outside function.
And then I would like to access them from outside.
In following code:
class User():
def __init__(self,id,name,email,password):
self.id = id
self.name = name
self.email = email
self.password = password
print('User created.')
class Category():
def __init__(self,id,category):
self.id = id
self.category = category
print('Category created.')
class Expenditure():
def __init__(self,id,category,price,date):
self.id = id
self.category = category
self.price = price
self.date = date
print('Expenditure created.')
def example_data():
"""Create example data for the test database."""
user1 = User("1", 'Daniel', 'dany#gmail.com', 'pass')
user2 = User(id="1", name='Daniel', email='dany#gmail.com', password='pass')
cat1 = Category(id="1", category="Food")
cat2 = Category(id="2", category="Flat")
expense1 = Expenditure(id="1", category=cat1.category, price=120, date="2017-12-01")
expense2 = Expenditure(id="2", category=cat2.category, price=230, date="2018-11-08")
example_data()
print(user1.name)
After this code I have NameError:
print(user1.name)
NameError: name 'user1' is not defined
Can I make this example working somehow?
This is about scopes of variables. user1 is only accessible in function block so you can't access it outside the function.
I don't know why you want to do this, but one solution is to make user1 a global variable:
def example_data():
"""Create example data for the test database."""
global user1
user1 = User("1", 'Daniel', 'dany#gmail.com', 'pass')
example_data()
print(user1.name)

Call the value of variable of method in another method of same class in python

I want to access father's name in the last function(enquiry()), and the name is present in the father() function. How to access value of the name variable in the father() function?
class family(object):
def __init__(self,members,surname):
self.members=members
self.surname=surname
def father(self,name,occupation):
self.name=name
self.occupation=occupation
def mother(self,name,occupation):
self.name=name
self.occupation=occupation
def children(self,numbers):
self.numbers=numbers
def enquiry(self):
print("The name of the father is "self.father(name))
family(4,'vora')
family.father('john','business')
family.enquiry()
This code corrects your syntactic errors but you should definitely take member P i's advice because this is ugly
class family(object):
def __init__(self,members,surname):
self.members=members
self.surname=surname
def father(self,name,occupation):
self.fathers_name=name
self.occupation=occupation
def mother(self,name,occupation):
self.mothers_name=name
self.occupation=occupation
def children(self,numbers):
self.numbers=numbers
def enquiry(self):
print("The name of the father is " + self.fathers_name)
f = family(4,'vora')
f.father('john','business')
f.enquiry()

Resources