Last active
August 21, 2023 13:47
-
-
Save makesomelayouts/354bb0afc8188192c26d716bc3046267 to your computer and use it in GitHub Desktop.
py objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| if __name__ == '__main__': | |
| class Comment: | |
| def __init__(self, txt): | |
| self.text = txt | |
| self.votes_qty = 0 | |
| def upvote(self): | |
| self.votes_qty += 1 | |
| comment1 = Comment('First comment') | |
| # print(comment1.__dict__) # {'text': 'First comment', 'votes_qty': 0} | |
| # print(comment1.text) # First comment | |
| # print(comment1.votes_qty) # 0 | |
| # print(dir(comment1)) # namespace for comment1 (the own attributes: text, votes_qty and the rest are: inherited from the class) | |
| """ | |
| [ | |
| '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', | |
| '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', | |
| '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'text', 'upvote', 'votes_qty' | |
| ] | |
| """ | |
| class Comment2: | |
| total_comments = 0 | |
| def __init__(self, text): | |
| self.text = text | |
| self.votes_qty = 0 | |
| Comment2.total_comments += 1 | |
| def upvote(self): | |
| self.votes_qty += 1 | |
| @staticmethod | |
| def merge_comments(first, second): | |
| return f'{first} {second}' | |
| def __add__(self, other): | |
| return (f'{self.text} {other.text}', self.votes_qty + other.votes_qty) | |
| my_comment = Comment2('My comment0') | |
| m_1 = Comment2.merge_comments('Ty', 'Yosh') | |
| print(m_1) # Ty Yosh | |
| m_2 = my_comment.merge_comments('Like', 'OK') | |
| print(m_2) # Like OK | |
| print(Comment2.total_comments) # 1 | |
| com1 = Comment2('First comment') | |
| com1.upvote() | |
| com2 = Comment2('Second comment') | |
| com2.upvote() | |
| print(com1 + com2) # ('First comment Second comment', 2) | |
| class ExtendedList(list): | |
| def print_list_info(self): | |
| print(f'List has {len(self)} elements') | |
| # this class is only for 'print(ExtendedList.__subclasses__())' check | |
| class MyExtendedList(ExtendedList): | |
| def print_list_info(self): | |
| print(f'List has {len(self)} elements') | |
| custom_list = ExtendedList([1, 2, 3]) | |
| custom_list.print_list_info() # List has 3 elements | |
| # object attribute search chain=custom list -> ExtendedList -> list -> object | |
| print(f'list of self-attributes of object name custom_list: {custom_list.__dict__}') # {} | |
| print(f'list of self-attributes of class ExtendedList: {ExtendedList.__dict__}\n') # {'__module__': '__main__', etc... | |
| print(f'list of self-attributes of class list: {list.__dict__}\n') # {'__new__': <built-in method __new__ etc... | |
| print(f'list of self-attributes of class object: {object.__dict__}') # {'__new__': <built-in method __new__ etc... | |
| print('\nlist subclasses: ' + str(list.__subclasses__()) + '\n') # [<class '__main__.ExtendedList'>] | |
| print(f'object subclasses: {object.__subclasses__()}\n') # [<class 'type'>, <class 'async_generator'>, <class 'bytearray_iterator'>, etc... | |
| print(ExtendedList.__subclasses__()) # [<class '__main__.MyExtendedList'>] | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| print(dict1['model']) | |
| # KeyError: 'model' | |
| print(dict1.get('model')) | |
| # None | |
| """ | |
| if __name__ == '__main__': | |
| # dict - unordered, indexing. | |
| print(dir(dict)) | |
| d = {} | |
| for i in range(6): | |
| key = input("Enter a key: ") | |
| value = input("Enter a value: ") | |
| d[key] = value | |
| print(d) # {'s': 's', '2': 'x', 'x': '1', '1234': '234', 'xzfds': 'asdasd', 'sdf79sdf79': '98asd89asd8'} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| if __name__ == '__main__': | |
| with open('new.txt', 'w') as file: # w=write | |
| file.write('First line in the new file\n') | |
| with open('new.txt') as file: # =read/r=read | |
| print(file.read()) # First line in the new file | |
| with open('new.txt', 'a') as file: # a=append | |
| file.write('Second line in the new file\n') | |
| with open('new.txt') as f: | |
| print(f.read()) | |
| # First line in the new file | |
| # Second line in the new file | |
| import csv | |
| with open('test.csv', 'w') as csv_file: | |
| writer = csv.writer(csv_file) | |
| writer.writerow(['user_id', 'user_name', 'comments_qty']) | |
| writer.writerow([1234, 'mxln', 23]) | |
| writer.writerow([1235, 'ismxln', 2]) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| if __name__ == '__main__': | |
| print('Hello, World!') | |
| def merge_lists_to_dict(keys, values): | |
| """ | |
| Merging lists to dictionary | |
| Args: | |
| keys (list): key from list1 to dict look key:value | |
| values (list): value from list2 to dict look key:value | |
| """ | |
| d = dict(zip(keys, values)) | |
| print(f'Your new dict: {d}') | |
| merge_lists_to_dict(['a', 'b', 'c'], [1, 2, 3]) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| if __name__ == '__main__': | |
| # 1 | |
| print('\t\t1') | |
| n = 5 | |
| squares = (num * num for num in range(n)) | |
| print(squares) | |
| for num in squares: | |
| print(num) | |
| # 2 | |
| print('\t\t2') | |
| from sys import getsizeof | |
| squares_gen = (num * num for num in range(10000)) | |
| print(getsizeof(squares_gen), type(squares_gen)) | |
| squares_list = [num * num for num in range(10000)] | |
| print(getsizeof(squares_list), type(squares_list)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def mult(a, b): | |
| return a * b | |
| mult = lambda a, b: a * b | |
| print(mult(10, 5)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| if __name__ == '__main__': | |
| # list - ordered, indexing. | |
| print(dir(list)) # or print(dir([])) | |
| # 1. | |
| elements = ['str', 123, True, [], {}, 10.5] | |
| del elements[2] # delete third element | |
| print(len(elements)) # print length of list | |
| print(elements[::-1]) | |
| list2 = ['a', 12] | |
| elements.extend(list2) | |
| print(elements) | |
| # 2. | |
| list1, list3 = [1,2,'3'], [3,2,'1'] | |
| list1 += list3 | |
| print(list1.__add__(list3)) | |
| print(list1) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # help('bs4') | |
| # help('time') | |
| import math | |
| print(math.pi, math.pow(5, 7)) | |
| print(dir(math)) # attributes of object math |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import re | |
| my_str = 'My nickname is Maxelone' | |
| res1 = re.search('Maxelone', my_str) # <re.Match object; span=(15, 23), match='Maxelone'> | |
| res2 = re.search('M......e', my_str) # <re.Match object; span=(15, 23), match='Maxelone'> | |
| print(res1, res2) | |
| print(re.search('^M.*name', my_str)) # <re.Match object; span=(0, 11), match='My nickname'> | |
| def check_mail(mail): | |
| mail_regexp = r'[a-zA-Z0-9_.]+@[a-zA-Z0-9]+\.[a-zA-Z0-9-.]+$' | |
| mail_check_pattern = re.compile(mail_regexp) | |
| result = 'valid' if mail_check_pattern.fullmatch(mail) else 'not valid' | |
| return (mail, result) | |
| print(check_mail('bs@gmail.com')) | |
| print(check_mail('bsgmail.com')) | |
| print(check_mail('bs@gmailcom')) | |
| print(check_mail('bs@mail.com')) | |
| print(check_mail('@gmail.com')) | |
| print(check_mail('bs@')) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| if __name__ == '__main__': | |
| # set - unordered, unindexing | |
| print(dir(set)) | |
| # only unique. | |
| set1 = {1123, 1234, 4231} | |
| set1.add(1) | |
| # set1.union(45234) | |
| # set1.update(46189) | |
| set2 = {1123, 1234, 52352} | |
| print(f'difference: {set1.difference(set2)}, intersection: {set1.intersection(set2)}') | |
| set3 = set1.intersection(set2) | |
| print(f'set1 {set1}, set3 {set3}') | |
| # convert tuple to a list | |
| set3 = list(set3) | |
| print(set3, type(set3)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| if __name__ == '__main__': | |
| # tuple - ordered, indexing. | |
| print(dir(tuple)) # () | |
| # .count() - count element in tuple, .index() - index element in tuple | |
| tuple1 = (1, "hello", [1, 2, 3], (4, 5, 6), {'a': 1, 'b': 2}) | |
| tuple2 = (7, 8.5, True, "world", {'c': 3, 'd': 4}) | |
| print(tuple1 + tuple2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment