def test_string_representation(): jane = Person('Jane') assert str(jane) == 'Jane' jane = Person('Jane', '*****@*****.**') assert str(jane) == 'Jane <*****@*****.**>' assert 'To: %s' % jane == 'To: Jane <*****@*****.**>' assert 'To: {}'.format(jane) == 'To: Jane <*****@*****.**>'
def test_instantiation_with_arguments(): jane = Person('Jane') assert jane.name == 'Jane' assert jane.email is None assert not hasattr(Person, 'name') john = Person('John', '*****@*****.**') assert john.name == 'John' assert john.email == '*****@*****.**'
def test_equality(): jane1 = Person('Jane') jane2 = Person('Jane') assert jane1 is jane1 assert jane1 is not jane2 assert jane1 == jane1 assert jane1 == jane2 assert not jane1 == 'Jane' assert not jane1 != jane2 assert jane1 != 'Jane' john1 = Person('John', '*****@*****.**') john2 = Person('John', '*****@*****.**') assert not john1 == john2 assert john1 != john2
def test_person(): "testing the person class" man = Person("Mark", 160, 35) assert man.name == "Mark" assert man.height == 160 assert man.strength == 35 assert man.hp == 100
def scrape_name_in_page(id_race, driver): # func to scrape names & performance from the list of results elements = driver.find_elements_by_tag_name("tr") limit = len(elements) for index in range(1, limit-6): try: time_race = driver.find_element_by_xpath('/html/body/div/div[3]/div/div[2]/table/tbody[2]/tr['+str(index)+']/td[3]').text name = driver.find_element_by_xpath('/html/body/div/div[3]/div/div[2]/table/tbody[2]/tr['+str(index)+']/td[4]').text category = driver.find_element_by_xpath('/html/body/div/div[3]/div/div[2]/table/tbody[2]/tr['+str(index)+']/td[5]').text club_name = driver.find_element_by_xpath('/html/body/div/div[3]/div/div[2]/table/tbody[2]/tr['+str(index)+']/td[6]').text score = driver.find_element_by_xpath('/html/body/div/div[3]/div/div[2]/table/tbody[2]/tr['+str(index)+']/td[7]').text except NoSuchElementException: time_race = driver.find_element_by_xpath('/html/body/div[1]/div[3]/div/div/table/tbody[2]/tr['+str(index)+']/td[3]').text # 2 possible type of table name = driver.find_element_by_xpath('/html/body/div[1]/div[3]/div/div/table/tbody[2]/tr['+str(index)+']/td[4]').text category = driver.find_element_by_xpath('/html/body/div[1]/div[3]/div/div/table/tbody[2]/tr[' + str(index) + ']/td[5]').text club_name = driver.find_element_by_xpath('/html/body/div[1]/div[3]/div/div/table/tbody[2]/tr[' + str(index) + ']/td[6]').text score = driver.find_element_by_xpath('/html/body/div[1]/div[3]/div/div/table/tbody[2]/tr[' + str(index) + ']/td[7]').text finally: time_race = format_time(time_race) person = Person(name) insert_person(person) id_person = fetch_runner_by_name(person.name) race_record = Record_Race_Person(id_person, id_race, score, time_race, category) insert_record_race_person(race_record) if club_name is not " ": club = Club(club_name) # once we collect data, we create python's obj and then we store what we need insert_club(club) id_club = get_club_id(club) club_record = Record_Club_Person(id_club, id_person) insert_record_club_person(club_record)
class TestPerson(TestCase): def setUp(self): self.person = Person(name='ramadan') self.classRoom1 = ClassRoom('1') self.classRoom2 = ClassRoom('2') def test_created(self): self.assertEqual('ramadan', self.person.name) self.assertEqual([], self.person.assigned_classes) def test_assign_to_class(self): self.assertEqual([], self.person.assigned_classes) self.person.assign_to_class(self.classRoom1) self.assertEqual([self.classRoom1], self.person.assigned_classes) self.person.assign_to_class(self.classRoom2) self.assertEqual([self.classRoom1, self.classRoom2], self.person.assigned_classes)
def test_methods(): jane = Person('Jane') assert jane.greet('John') == 'Jane says hello to John' assert jane.greet('Robot') == 'Jane says hello to Robot' jane.name = 'Janet' assert jane.greet('Johnny') == 'Janet says hello to Johnny' assert Person('John').greet('Jane', greeting='hi') == 'John says hi to Jane'
def newGame(): session['user'] = randomString() P = Person() G = GameState(P, startRoom) DATA[session['user']] = {'Game': G, 'directions': directions} sys.stdout = DATA[session['user']]['stdout'] = StringIO() DATA[session['user']]['stdoutLength'] = len( DATA[session['user']]['stdout'].getvalue()) return redirect(url_for('index'))
def newGame(): print(app.secret_key) print(session) P = Person() G = GameState(P, startRoom) session['Game'] = G session['Directions'] = directions sys.stdout = session['stdout'] = StringIO() session['stdoutLength'] = len(session['stdout'].getvalue()) return redirect(url_for('index'))
def addPerson(session): demoDetails = _parseUserInput("Enter basic demographic details in the following format: \n firstName(String) lastName(String) genderFemale(Boolean) birthDate(Datetime):", 4) demoDetails[0] = _setString(demoDetails[0]) demoDetails[1] = _setString(demoDetails[1]) demoDetails[2] = _setString(demoDetails[2]) demoDetails[3] = _reIssueDateFn(demoDetails[3]) person = Person(firstName=demoDetails[0], lastName=demoDetails[1], genderFemale=bool(strtobool(str(demoDetails[2]))), birthDate=demoDetails[3]) session.add(person) session.commit() return person
def option_C(): """ This function allows the user to create a new project. """ project_name = str(input("\nEnter the project name: ")) number_members = utils.get_number_members() members = {} for i in range(number_members): member_name = str( input("\t Enter the name of team member {}: ".format(i + 1))) members[member_name] = Person(member_name, {}) project_dict[project_name] = Project(project_name, number_members, members) main()
def get_people(): # Create an empty list data = {} # get rows of data from our file rows = read_rows("people.csv") # Iterate over each row we get back from `read_rows` for row in rows: # Create a `Person` object using the `id`, and `name` stored in the row: ['123', 'Bob'] saved_person = Person(row[0], row[1], int(row[2])) # add this to our temp dict data.update({saved_person.id: saved_person}) # Return the dictionary of people back to the function caller return data
def create_person(): # Prompt user to enter name name = input("Please enter name: ") # Create `age` variable age = None # While user hasn't entered a valid age while age == None: try: # Prompt user to enter age age = int(input("Please enter age: ")) except: print('Pease try again') # Create a new `Person` using the class constructor method new_person = Person(len(people), name, age) # Add this `Person` to our dictionary of `people` people.update({new_person.id: new_person})
from classes import Person john = Person("Jon Doe") john.age = 5654 print(f"John name {john.name} Age: {john.age}")
from classes import AccountP as Account a1 = Account('John Olsson', '19371554951', 20000) a1.deposit(1000) a1.withdraw(4000) a1.withdraw(3500) a1.dump() print a1._balance # it works, but a convention is broken print a1.get_balance() # correct way of viewing the balance a1._no = '19371554955' # this is a "serious crime" from classes import Person p1 = Person('Hans Petter Langtangen', office_phone='67828283', email='*****@*****.**') p2 = Person('Aslak Tveito', office_phone='67828282') p2.add_email('*****@*****.**') phone_book = [p1, p2] # list for person in phone_book: person.dump() phone_book = {'Langtangen': p1, 'Tveito': p2} # dict is better for person in sorted(phone_book): phone_book[person].dump() from classes import Circle c = Circle(2, -1, 5) print 'A circle with radius %g at (%g, %g) has area %g' % \ (c.R, c.x0, c.y0, c.area()) from classes import Derivative
from classes import Person, Auto person1 = Person("Tom") person1.displey_info() person2 = Person("Sam") person2.displey_info() bmw = Auto("BMW") bmw.move(65)
def test_eat(): "testing the eat function" man = Person("Mark", 160, 35) man.hp = 50 man.eat() assert man.hp == 100
def test_punch(): "testing the punch function" man = Person("Mark", 160, 35) other_man = Person('Trevor', 180, 40) assert man.punch == "Mark punched Trevor" assert other_man.hp == 90
def test_introduce(): "testing the introducing function" man = Person("Mark", 160, 35) assert man.introduce == "Hello, my name is Mark"
# Инкапсуляция from classes import Person # import classes person1 = Person(name='John') person1.print_info() person2 = Person(name='Katy') # person2.__age = 30 # print(person2.get_age()) # person2.set_age(25) print(person2.age) person2.age = 35 person2.print_info()
from classes import Person, Employee person2 = Person('Katy', 32) person2.age = 40 person2.print_info() employee = Employee('Nik', 22) employee.print_info() employee.more_info()
from classes import Person, Cars p = Person("Alexander", "Ivanov") c = Cars("BMW", "E30") c1 = Cars("BMW", "E39") p.print_person() c.print_car() c1.print_car()
def update_runner_id( runner: Person): # with this function we update the id of the runner tmp = None # in the case we need it tmp = fetch_runner_by_name(runner.name) runner.set_id(tmp[1])
def get_person_object_from_excel(owner='N/A', path='test.xlsm', start_week=4, end_week=4): """ Returns List of Work objects containing data from all work between start- and end-week """ from utils.utils_time import xldate_as_datetime sheet_prefix = 'Uke' person = Person(owner, [], start_week, end_week) print(f'\nreading from {path}...') start_execution = round(time.time() * 1000) workbook = xlrd.open_workbook(path) for i in range(start_week, end_week + 1): sheet_name = f'{sheet_prefix}{i}' try: worksheet = workbook.sheet_by_name(sheet_name) except Exception as ex: print_msg(f'ERROR: {str(ex)} in \'{path}\'') end_week = i - 1 break # Loop through all data from (A10:E10) vertically cur_row_x = 10 - 1 # Start row 10 while True: date_float = worksheet.cell(cur_row_x, colx=0).value if type(date_float) != float: break # Stop iteration if end vertically tmp_date_tuple = datetime.datetime( *xlrd.xldate_as_tuple(date_float, workbook.datemode)) tmp_week_number = i tmp_time_start = worksheet.cell(cur_row_x, colx=1).value * 24 tmp_time_end = worksheet.cell(cur_row_x, colx=2).value * 24 tmp_duration = xldate_as_datetime( worksheet.cell(cur_row_x, colx=3).value, workbook.datemode) tmp_type_of_work = worksheet.cell(cur_row_x, colx=4).value for key in WorkSession.get_work_type_dictionary(): if search(key.lower(), str(tmp_type_of_work).lower()): tmp_type_of_work = WorkSession.get_work_type_dictionary( ).get(key) tmp_backlog_item_nr = worksheet.cell(cur_row_x, colx=5).value if any(tmp_backlog_item_nr == c for c in ['N/A', '', ' ', '-1']): tmp_backlog_item_nr = '0' # Set to 0 if no backlog-item # Create work object and append it to list temp_work = WorkSession(date=tmp_date_tuple, week_number=tmp_week_number, time_start=tmp_time_start, time_end=tmp_time_end, duration=tmp_duration, work_type=tmp_type_of_work, item_nr=tmp_backlog_item_nr) person.WorkSession_list.append(temp_work) cur_row_x += 1 print_msg(f'{round(time.time() * 1000) - start_execution}ms.') print_msg( f'Total work duration ->{person.get_total_work_duration()} week {start_week} to {end_week}' ) return person
# # Create a new class named **Person**. Give the class the instance # attributes "name" and "ssn". Make "ssn" a private attribute. The values for # the attributes should be sent to the constructor as arguments. # Create a *get* property for "ssn". # # In the code below create a new variable called **per** and set it to a new # instance of Person. Give it the name `Farseer` and ssn `578118-6946`. # # # Answer with per\'s getter for ssn. # # Write your code below and put the answer into the variable ANSWER. # per = Person("Farseer", "578118-6946") ANSWER = per.get_ssn() # I will now test your answer - change false to true to get a hint. dbwebb.assert_equal("1.1", ANSWER, False) # """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" # Exercise 1.2 (2 points) # # Create a new class named **Address**. Give the class the instance # attributes "city", "state" and "country". The values for the attributes # should be sent to the constructor as arguments. # Create the magic method **_\_str_\_**, in Address, it should return # `"Address: <city> <state> <country>"` (replace the \<city\> with the value # of the attribute city...).
from classes import Person # import classes person1 = Person('John') person1.print_info() person2 = Person('Katy') person2.print_info()
from classes import Person p1 = Person("Tom", "Smith", 170, 78) p2 = Person("Marta", "Smith", 150, 58) p3 = Person("Chris", "Smith", 100, 28) p4 = Person("Adam", "Smith", 70, 18) p5 = Person("Ben", "Smith", 178, 88) list_people = [] list_people.append(p1) list_people.append(p2) list_people.append(p3) list_people.append(p4) list_people.append(p5) for i in list_people: print(i.first_name)
from classes import Person # import classes person1 = Person('liza') person1.print_info() person2 = Person('mama') # person2._age = 30#work age = 30 # print(person2.__age)# error не относится к классу # person2.__age = 30 # print(person2._Person__age) # print(person2.get_age())# __age =20 # person2.set_age(40)#40 print(person2.age)#<bound method Person.age of <classes.Person object at 0x000002B8DCB9D668>> person2.age = 35 person2.print_info()# Name: mama Age: 30 # person1 = Person('liza') # person1.print_info()
import json from Serialization import Serialization as ser from classes import Person a = Person("Andrey", 11) ser.save_to_file(a, "test1.json", True, False) print(ser.load_object_from_file("test1.json", "classes"))
from classes import Person person = Person("Isxoqjon") print(person.getName())
from classes import Person, Employee person = Person('Katy', 30) person.age = 35 person.print_info() employee = Employee('Job', 25, 'Google') employee.print_info() employee.more_info() employee.__str__() print(employee)