class Artist:
def __init__(self, name, dob):
self.name = name
self.dob = dob
def get_name(self):
return self.name
def get_dob(self):
return self.dob
def age(self):
if get_date_today() < (2013, 12, 27):
return self.age
else:
return self.age + 1
def get_date_today():
return (2013, 10, 30) #'today'
hw = Artist("Hayley Williams", (1988, 12, 27))
print(hw.age()) # 24 if 'today' is < (2013, 12, 27), 25 if 'today' is >= (2013, 12, 27)
How do I do an addition in the else loop. It can't work here because I can't add 1 to the method. So what is wrong ?
from datetime import datetime
class Artist:
def __init__(self, name, dob):
self.name = name
self.dob = dob
def get_name(self):
return self.name
def get_dob(self):
return self.dob
def age(self):
return ((datetime.today() - datetime(*self.dob)).days)/365
datetime is module in python which use to perform date realted operation. datetime.today will return you current date.
You do not have a self.age variable in your __init__ loop. Try this instead:
class Artist:
def __init__(self, name, dob, age):
self.name = name
self.dob = dob
self.age = age
def get_name(self):
return self.name
def get_dob(self):
return self.dob
def get_age(self):
if get_date_today() < (2013, 12, 27):
return self.age
else:
return self.age + 1
You are trying to return an age in your method age() which you have no data about. Decide where to get that data from and store it, then you can return it in the method.
One way to achieve this is to get the data upon object construction:
def __init__(self, birthday):
self.birthday = birthday
# store also your other data like name and dob
then you can use it to compute the age:
def age(self):
if get_date_today() < (2013, 12, 27):
return get_date_today() - self.birthday
else:
return get_date_today() - self.birthday + 1
# this assumes of course that you are using a date type which understands subtraction
But there are other ways like getting the age from a data base or just returning the age given on construction (see sshashank124's answer for that).
Related
Could someone explain to me how to correctly use classmethod with inheritance in Python?
I need to create two classmethod methods:
to makefull-timeime employee.
to make a part-time employee in Employee class which is inhering from BaseEmployee.
Seem that I fully don't understand a concept:(
Ok, so the question is how to properly create a classmethod and then
how to create a fulltime employee?
Thanks
from datetime import datetime
class Error(Exception):
"""Base class for exception"""
pass
class InvalidDateOfEmployment(Error):
"""Except bigger date then today and seniority more than 50 years"""
pass
class Application:
#staticmethod
def main(self):
name = input('Name: ')
last_name = input('Last name: ')
date_of_employement = datetime.strptime(input('Date of Employement (2022-03-02): '), '%Y.%m.%d')
if Application.date_of_employment_validation(datetime.today(), date_of_employement):
raise InvalidDateOfEmployment
employee = BaseEmployee(name, last_name, date_of_employement)
#staticmethod
def date_of_employment_validation(today: datetime, date: datetime):
diff = today - date
diff_in_years = round(diff.days / 365.25)
return 50 > diff_in_years > 0 #diff_in_years < 50 and diff_in_years > 0
class BaseEmployee:
def __init__(self, name, last_name, date_of_employement):
self.name = name
self.last_name = last_name
self.date_of_employement = date_of_employement
self.now = datetime.now()
#property
def employment_time(self):
return (self.now - self.date_of_employement).days
def __lt__(self, other):
return self.employment_time < other.employment_time
def __repr__(self):
return self.name, self.last_name, self.date_of_employement
class Employee(BaseEmployee):
def __init__(self, bonus, type_of_employment, hour_pay_rate, name, last_name, date_of_employement):
super().__init__(name, last_name, date_of_employement)
self.bonus = bonus
self.type_of_employment = type_of_employment
self.hour_pay_rate = hour_pay_rate
#classmethod
def create_fulltime(cls, bonus, type_of_employment, hour_pay_rate):
return cls(bonus, 160, hour_pay_rate)
# #classmethod
# def create_partime(cls, name, last_name, date_of_employement, bonus, hour_pay_rate):
# return cls(name, last_name, date_of_employement, bonus, hour_pay_rate, 80)
def calculate_sallary(self):
return self.hour_pay_rate * self.type_of_employment + self.bonus
if __name__ == '__main__':
Application.main()
def test_sort_employees():
#given
a = BaseEmployee('A', 'A', datetime(2020, 12, 10))
b = BaseEmployee('B', 'B', datetime(2020, 10, 10))
employees = [a, b]
#when
sorted_employees = sorted(employees)
#then
assert sorted_employees[0] == a
For example:
from datetime import datetime
class Employee:
bonus = 1
base_hpr = 300
#classmethod
#property
def salary_bonus_multiplier(cls):
return cls.bonus
def __init__(self, name, last_name, date_of_employement, hour_pay_rate = base_hpr):
self.name = name
self.last_name = last_name
self.date_of_employement = date_of_employement
self.hour_pay_rate = hour_pay_rate
self.now = datetime.now()
#property
def employment_time(self):
return (self.now - self.date_of_employement).days
def calculate_sallary(self):
return self.employment_time * self.hour_pay_rate * self.salary_bonus_multiplier
def __lt__(self, other):
return self.employment_time < other.employment_time
def __repr__(self):
return self.name, self.last_name, self.date_of_employement
class HalfTimeEmployee(Employee):
bonus = 0.5
class FullTimeEmployee(Employee):
pass
if __name__ == '__main__':
a = HalfTimeEmployee('A', 'A', datetime(2020, 10, 10))
b = FullTimeEmployee('B', 'B', datetime(2020, 10, 10))
print(a.calculate_sallary(), b.calculate_sallary())
classmethod mean to use only class avaluable variables.
Inheritance helps to change them in a particular case.
I want to know how to get all the values of student0 instance without using the print(student0.name, student0. age) method when I have the code below.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
student0 = Student("Lee", "22")
student1 = Student("Kim", "23")
You can use the following code :
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return "% s % s" % (self.name, self.age)
student0 = Student("Lee", "22")
student1 = Student("Kim", "23")
print(student0)
I want to call a method when an attribute of an object is written. For example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def isAdult(self):
print(True if self.age>=21 else False)
If i want to call .isAdult() when an object's age is written a value, how can I achieve this?
I heard of people suggesting to use decorators, but they didn't give more details.
What you want to have is called a setter. You must use new-style classes and extend object to use them:
class Person(object):
def __init__(self, name, age):
self.name = name
self._age = age
def isAdult(self):
print(self.age >= 21)
#property
def age(self):
return self._age
#age.setter
def age(self, value):
self._age = value
self.isAdult()
Then, for example:
p = Person("John Doe", 12)
p.age = 16
p.age = 25
will print
False
True
you can use decorator in class like below.
In below code, isAdultDeco will be call when you create Person object.
class Person:
def isAdultDeco(func):
def foo(self, name, age):
func(self, name, age)
print(True if self.age>=21 else False)
return foo
#isAdultDeco
def __init__(self, name, age):
self.name = name
self.age = age
Person('a',22) # True
Person('a',20) # False
Attempting to compare two objects' data members; however, the error message has no specific details, which leaves me with little information on how to go about correcting it
class Person:
def __init__(self, name, age, id):
self.name = name
self.age = age
self.id = id
def same_person(Person lhs, Person rhs):
return lhs.id == rhs.id
person1 = Person("David Joyner", 30, 901234567)
person2 = Person("D. Joyner", 29, 901234567)
person3 = Person("David Joyner", 30, 903987654)
# print calls provided as part of an exercise: not my implementation
print(same_person(person1, person2))
print(same_person(person1, person3))
Python 3.6.5
Command: python person.py
Error message
If it were an indentation level the following error is displayed
same_person is a method of the class Person and should take just an argument as input. It should be defined as:
def same_person(self, other):
return self.id == other.id
and called as
person1.same_person(person2)
or you could override the __eq__ method (i.e., ==).
def __eq__(self, other):
return self.id == other.id
in order to be able to do it as person1 == person2
The other answers are correct and provide the best way to do it, but I realized that you wrote:
print calls provided as part of an exercise: not my implementation
print(same_person(person1, person2))
print(same_person(person1, person3))
The exercise probably wants you to define a function outside the class. You can do that by removing that function from the class and writing it un-indented outside the class (without providing class type too). For example:
class Person:
def __init__(self, name, age, id):
self.name = name
self.age = age
self.id = id
def same_person(lhs, rhs):
return lhs.id == rhs.id
person1 = Person("David Joyner", 30, 901234567)
person2 = Person("D. Joyner", 29, 901234567)
person3 = Person("David Joyner", 30, 903987654)
print(same_person(person1, person2))
print(same_person(person1, person3))
class Person:
def __init__(self, name, age, id):
self.name = name
self.age = age
self.id = id
def same_person(self, lhs, rhs):
return lhs.id == rhs.id
you dont have to define lhs and rhs type in python unless you are using typings.
Quite a few mistakes:
The arguments in the method cannot be preceded by the Person classname
You have not defined instances person1, person2 and person3
If you define an instance method (same_person), it should be used ON an instance.
This is what I would do:
class Person:
def __init__(self, name, age, id):
self.name = name
self.age = age
self.id = id
def same_person(self, other):
return self.id == other.id
person1 = Person("Bob", 25, 1)
person2 = Person("Mike", 33, 1)
person3 = Person("Maria", 28, 2)
print(person1.same_person(person2))
print(person1.same_person(person3))
Output:
True
False
You'd better rewrite eq to compare objects:
class Person:
def __init__(self, name, age, id):
self.name = name
self.age = age
self.id = id
def __eq__(self, other):
return self.id == other.id
person1 = Person("Bob", 25, 1)
person2 = Person("Mike", 33, 1)
person3 = Person("Maria", 28, 2)
print(person1 == person2)
print(person1 == person3)
>>> True
>>> False
https://devinpractice.com/2016/11/29/python-objects-comparison/
I am writing my own class and methods and I have it all complete except the part of using localtime() to determine a user's age. I have never used localtime(). so I don't know how to implement it in the code. Currently, in the manner it's written, it returns a bound error.
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 15 22:10:07 2015
#author: Daddy
"""
class Person ():
def __init__(self, name, birthyear):
self.name = name
self.birthyear = birthyear
def age(self, birthyear):
age = 2015 - self.birthyear
return age
def name(self):
return self.name
class Instructor(Person):
def __init__(self, name, birthyear, degree):
self.name = name
self.birthyear = birthyear
self.degree = degree
def degree(self, degree):
return (self.degree)
class Student(Person):
def __init__(self, name, birthyear, major):
self.name = name
self.birthyear = birthyear
self.major = major
def major(self, major):
return (self.major)
import datetime
def age(self):
return datetime.datetime.now().year - self.birthyear
Note you don't need to pass birthyear because it's in self, and return is the value of the called function.