I'm writing a code to understand inheritance and here is what I did so far.
class Master:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.full_name = first_name + last_name
self.email_id = (first_name + last_name + '#vit.com').lower()
class Student(Master):
def __init__(self, first_name, last_name, reg_num):
super().__init__(first_name, last_name)
self.reg_num = reg_num
def __str__(self):
return self.first_name + " " + self.last_name
class Proctor(Master):
def __init__(self, first_name, last_name, students=None):
super().__init__(first_name, last_name)
if students is None:
self.students = []
else:
self.students = students
stud_1 = Student('kishan', 'B', '16BEI0067')
proctor_1 = Proctor('Mani', 'Mozhi', [stud_1])
print(proctor_1.students)
When the last print statement excutes, instead of getting the details of stud_1, I get [<__main__.student object at 0x7f362206a908>]
What is going wrong?
You need to add an __str__() method to your student class to indicate how it should be printed:
class Student(Master):
def __init__(self, first_name, last_name, reg_num):
super().__init__(first_name, last_name)
self.reg_num = reg_num
def __str__(self):
return self.first_name + " " + self.last_name
You are printing the object itself, not the attributes.
To print those you have to either go through the list with a for loop and call the attributes in this way:
for s in proctor_1.students:
print(s.first_name, s.last_name) # and so on
Or you could implement the __str__ dunder method:
def __str__(self):
return s.first_name + " " + s.last_name
(Or however you want the output to look like.)
There are a number of ways that you could print the attributes of an object in Python. Here's one other way. This will print the attributes of the object:
for attr in dir(proctor_1):
if hasattr(proctor_1, attr):
print("proctor_1.%s = %s" % (attr, getattr(proctor_1, attr)))
You could also wrap this in a dump function and then call dump(obj) to print out the attributes.
Related
How can i fix this?
class Employee:
def __init__(self, **employe_data):
self.employee_id = employe_data['employee_id']
self.first_name = employe_data['first_name']
self.last_name = employe_data['last_name']
self.born = employe_data['born']
self.photo = employe_data['photo']
self.moto = employe_data['moto']
self.position_company = employe_data['position_company']
def __str__(self) -> str:
employee = []
if self.first_name is not None:
employee.append(self.first_name)
if self.last_name is not None:
employee.append(self.last_name)
return " ".join(employee)
error name is
self.first_name = employe_data['first_name']
KeyError: 'first_name'
also in mysql, row is called first_name, thanks in forward
What am I missing in my code? I've tried different variations of this code, maybe five. I've run the code and I get the statement to execute, but there is still something missing. The name doesn't print along with it. Attached is a screenshot of the parameters that were given.
enter image description here
enter image description here
class Citizen:
"""
this class is to describe a citizen of the City of Python
"""
def __init__(self, first_name, last_name):
self.first_name = Rey
self.last_name = Rizo
def full_name(x):
x = self.first_name + self.last_name
def greeting(greet):
full_name = raw_input(full_name)
return greet + x
print("For the glory of Python!")
class Citizen:
"this class is to describe a citizen of the City of Python"
def __init__(self, first_name, last_name):
self.first_name = first_name #this is an instance variable
self.last_name = last_name
def full_name(self): #This is an instance method
return self.first_name + " " + self.last_name #This took the 2 instance variables and put them together
greeting = "For the glory of Python!"
This is what worked for me.
class Citizen:
"""a citizen of the City of Python"""
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def full_name(self):
return (f'{self.first_name} {self.last_name}')
greeting = 'For the glory of Python!'
This worked for me.
class Citizen:
"""
this class is to describe a citizen of the City of Python
"""
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def full_name():
return self.first_name + self.last_name
def greeting(greet):
return greet + self.full_name()
When you initiate a new citizen, use:
citizen = Citizen(“first_name”, “last_name”)
To print the name:
print(citizen.full_name)
To greet:
print(citizen.greeting(“Hello”))
I was wondering how to create a function to set the key of a dictionary. Consider the following class:
class Dog:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
Now lets instantiate the object:
a_dog = Dog("Berty", "Hollows")
Now I want to create a function, which returns either the first name or the last name, depending on which parameter I pass into it. My idea was something like:
def return_dogs_name(dog, get_dict_key(x)):
return dog.get_dict_key(x)
with
def get_dict_key(x):
return x
however, that does not work.
My desired output would look like
return_dogs_name(a_dog, get_dict_key("first_name"))
>>> Berty
How would such a function look like?
You can make use of getattr:
class Dog:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def return_dogs_name(dog, attrName):
return getattr(dog, attrName)
a_dog = Dog("Berty", "Hollows")
print(return_dogs_name(a_dog, 'first_name'))
Out:
Berty
You can create a dictionary within your function
class Dog:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
a_dog = Dog("Berty", "Hollows")
def return_dogs_name(dog,which_name):
return {'first': dog.first_name,'last': dog.last_name}.get(which_name,'unknown')
print(return_dogs_name(a_dog,'last'))
Output :
Hollows
For example, if I have the function:
def to_full_name(first_name, last_name=None): # Note that 'last_name' is not required, so an error will not occur
return '{} {}'.format(first_name, last_name)
# ...
a = to_full_name('John')
How can I add the second argument to the 'a' variable later down the line? ex:
a.set_argument('last_name', 'Doe')
For this particular problem I would recommend a class.
class Person:
def __init__(self, first_name=None, last_name=None):
self.first_name = first_name
self.last_name = last_name
def set_first_name(self, name):
self.first_name = name
def set_last_name(self, name):
self.last_name = name
def to_full_name():
return '{} {}'.format(self.first_name, self.last_name)
Then we change it as follows
person = Person("John")
person.set_last_name("Doe")
print(person.to_full_name())
We can also change the values directly
person = Person()
person.last_name = "Doe"
person.first_name = "John"
print(person.to_full_name())
I am new in Python Classes. I want pass a datetime object to the Person class as birth_date.
This is what I have now:
import datetime
class Person:
def __init__(self, first_name, last_name, birth_date):
self.first_name = first_name
self.last_name = last_name
def fullname(self):
return self.first + ' ' + self.last_name
You can use datetime.strptime():
from datetime import datetime
class Person:
def __init__(self, first_name, last_name, birth_date):
self.first_name = first_name
self.last_name = last_name
self.birth_date = datetime.strptime(birth_date, '%b %d %Y')
def fullname(self):
return self.first + ' ' + self.last_name
person = Person('John', 'Doe', 'Jun 1 2005')
print(person.birth_date)
Returns:
2005-06-01 00:00:00
You assumed a particular date format, which you can modify as you see fit. Reference to docs here.