Class and method print mistake - python-3.x

`
class Dog():
spicies="mammal"
def __init__(self,breed,name):
self.breed =breed
self.name =name
def bark(self,number):
print(f"woof {self.name} is my name and the number is{number}")
mydog= Dog(breed='lab',name="kal",)
print(mydog.breed,mydog.name,mydog.spicies,mydog.bark(1))
`
output: woof kal is my name and the number is1
lab kal mammal None
why it print first and there is none where it was suppose to print what is wrong ?
`
class Dog():
spicies="mammal"
def init(self,breed,name):
self.breed =breed
self.name =name
def bark(self,number):
print(f"woof {self.name} is my name and the number is{number}")
mydog= Dog(breed='lab',name="kal",)
print(mydog.breed,mydog.name,mydog.spicies,mydog.bark(1))
`
> output: woof kal is my name and the number is1
lab kal mammal None
**why it print first and there is none where it was suppose to print what is wrong ?**

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

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)

Why do i get a type error when using super()?

I just started learning about classes and inheritance in Python 3. I want to print the name of a student, which is inherited from the superclass Person. Unfortunately I keep getting a TypError.
code:
class Person(object):
def __init__(self, name="Mike", age = 25, place_of_birth="Stockholm"):
self.age = age
self.name = name
self.place_of_birth = place_of_birth
class Student(Person):
def __init__(self, name, age, university = "University of Stockholm", gpa = 8):
super().__init__(name, age)
self.university = university
self.gpa = gpa
I then like to print the name of the student by calling:
student1 = Student()
print(student1.name)
But I keep getting this error message:
Traceback (most recent call last):
TypeError: init() missing 2 required positional arguments: 'name' and 'age'
If you want Student to always default to the name and age of the Parent class then you don't want Student to take a name and age value.
class Student(Person):
def __init__(self, university = "University of Stockholm", gpa = 8):
super().__init__() # runs parent __init__ taking no values
self.university = university
self.gpa = gpa
>>> student1 = Student()
>>> student1.name
'Mike'
>>> student1.age
25
When you use super().__init__(name, age) you are wanting to pass the name and age given to the Student class to the Parent class. But since you don't want to pass anything it is getting errors.
Now, if you want the Student class to be able to take values as well as default to the ones provided by the parent class you can do this.
class Student(Person):
def __init__(self, name = None, age = None, university = "University of Stockholm", gpa = 8):
if name is None and age is None:
super().__init__()
else:
super().__init__(name, age)
self.university = university
self.gpa = gpa
What happens here is if no name or age is provided if name is None and age is None then it defaults to the values from Person class. However if both the name and age are provided, then it will use those values.
>>> student1 = Student()
>>> student1.name
'Mike'
>>> student1.age
25
>>> student2 = Student('Bill', 19)
>>> student2.name
'Bill'
>>> student2.age
19
The __init__() method of Student takes 2 positional arguments: name and age. You need to specify those arguments when creating a new instance:
student1 = Student('eppe2000', 20)
print(student1.name)
If you instead want the class Student to default to class Person default arguments, in case they have not been specified, you can do it like this:
class Person(object):
def __init__(self, name="Mike", age=25, place_of_birth="Stockholm"):
self.age = age
self.name = name
self.place_of_birth = place_of_birth
class Student(Person):
def __init__(self, university="University of Stockholm", gpa=8, **kwargs):
super().__init__(**kwargs)
self.university = university
self.gpa = gpa
>>> s = Student()
>>> s.name
'Mike'
>>> s = Student(name="Daniele")
>>> s.name
'Daniele'
Basically you forward all the keywords arguments that are unknown to the class Student to its parent class. Not that if you specify an invalid keyword (i.e: 'surname') you will get a TypeError because neither Student or Person specify a keyword argument with key 'surname'.
If you need info about **kwargs check this post: https://stackoverflow.com/a/36908/3477005

Resources