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
Related
class Person:
def __new__(cls, *args):
if not all(isinstance(x, str) for x in args):
raise TypeError(
f'invalid argument {1??} in {invalid_person??}'
f'{last_name??} must be string'
)
return super().__new__(cls)
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def __str__(self):
return f'{self.first_name} - {self.last_name}'
if __name__ == '__main__':
person = Person('john', 'dow')
print(person)
# error here
invalid_person = Person('john', 1)
Hello. this is example.
how to output an error in which place the error occurred, the name of the argument, the name of the attributes in the class and the name of the instance of the class?
Or maybe there is a better way to implement validation when instantiating a class?
I have this class and method:
class Person(object):
def __init__(self, name):
self.name = personname
self.surname = personsurname
def changenameorsurname(self, x, y):
self.x = y
return
AdamSmith = Person ("Adam", "Smith")
I want to use method changenameorsurname to change AdamSmith's name or surname, but if I use this code I'm getting a NameError"
AdamSmith.changenameorsurname(personname, Dave)
Result:
NameError: name personname is not defined.
Is there elegant way to reference personname in code like this? Or do I have to make two separate methods like this?
def changename(self, y):
self.name = y
return
AdamSmith.changename(Dave)
There are a couple of problems. Your init method needs to be fixed so you can properly construct a Person object. You can have your changenameorsurname() method take one argument that is a name and a second argument that determines whether that name is the first name or the surname. Here, I have set the default to first name.
class Person:
def __init__(self, first_name, surname):
self.first_name = first_name
self.surname = surname
def changenameorsurname(self, name, first = True):
if first:
self.first_name = name
else:
self.surname = name
def __str__(self):
return f'{self.first_name} {self.surname}'
some_guy = Person ("Adam", "Smith")
print(some_guy) #Adam Smith
some_guy.changenameorsurname("Michael")
print(some_guy) #Michael Smith
some_guy.changenameorsurname("Jones", first=False)
print(some_guy) #Michael Jones
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”))
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'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.