Planet sim and Etch added, working properly AFAIK

This commit is contained in:
ben 2022-07-19 16:40:55 -05:00
commit 88f86dc04f
19 changed files with 638 additions and 0 deletions

57
Classes and OOP/cat.py Normal file
View file

@ -0,0 +1,57 @@
import random
import time
from pet import Pet
class Cat(Pet):
def __init__(self, name='Garfield', color='brown', breed='cat',
chance_of_overthrowing_major_world_government=100): # self is equivalent of this
"""
Initializes instance of Dog class.
:param color: color of Dog
:param breed: breed of Dog
:param chance_of_overthrowing_major_world_government: the chance of the Cat overthrowing world governments
"""
# Can add __ before variable name to make it a private
# variable, so it can't be directly accessed. Only through methods.
super().__init__(name, color, breed)
self.__chance_of_overthrowing_major_government = chance_of_overthrowing_major_world_government
@property
def chance_of_overthrowing_major_government(self):
return self.__chance_of_overthrowing_major_government
@staticmethod
def __meow():
print('meow, meow')
@staticmethod
def __purr():
print('*vibration noise between approximately 25 hz and 150 hz*')
@staticmethod
def laser():
Cat.__meow()
print('*pounce*')
time.sleep(1)
print('*pounce pounce*')
def __str__(self):
return f'{super().name} is a {super().color} {super().breed} that has a ' \
f'{self.__chance_of_overthrowing_major_government}% chance of overthrowing a major government.'
def __eq__(self, other):
if not isinstance(other, Cat):
raise TypeError
if self.color == other.__color and self.__breed == other.__color and \
self.__chance_of_overthrowing_major_government == other.__color:
return True
return False
@staticmethod
def make_noise():
num = random.randint(0, 1)
if num == 0:
Cat.__meow()
else:
Cat.__purr()

View file

@ -0,0 +1,73 @@
### Object Oriented Programming (OOP)
- Object definition: An object is an instance of a class
- For example, `str` is not an object, but in `word = 'hi'` word is an object (an instance of the `str` class)
- Objects use allocated memory
- A physically entity (digitally). You can't hold it, but an object is a thing. A class is an idea for how to make an object.
- Characteristic/Attributes objects have
- Identity
- Each object has its own identity, such as a memory address. Two variables may reference the same object, but the identity is the memory address of the object.
- State
- The state is all the attributes of the object with values assigned to them. Such as a plane object having a fuel object. Anytime you change the fuel object, you change the plane object's state.
- Behavior
- Example: \_\_eq\_\_ method in `str`.
- Always use behavior to access state (getter and setters), don't access directly.
- Class definition: A class is the code that instructs a program how a particular object should be built.
- A class is used to create many objects.
- OOP Characteristics:
- Encapsulation
- Class, variable, getter, and setter all in one thing.
```
class Cookie:
def __init__(self):
self.flavor = flavor
def get_flavor(self):
return self.flavor
def set_flavor(self, flavor):
self.flavor = flavor
```
- Abstraction (user interface vs private interface)
- `.sort()` does stuff, you make it easy, and you don't care how it does it (as long as it's reasonably efficient).
- Inheritance
- is-a relationship
- Ferrari is-a Car
- Can use methods of parent class, such as `__str__`, and add on to it with its own `__str__`.
- Polymorphism
- Always used with inheritance.
- Overriding a parent class's method with a different method with different or extra functionality.
- In the Ferrari class, `__str__()` overrides the Car `__str__()`, and can provide extra functionality, such as multiplying the cost to repair because it's a Ferrari.
### Classes
- Magic methods (also called dunder methods) (override methods):
- If: `__eq__(), __gt__(), __ge__(), __lt__(), __le__(), __and__(), __or__()`
- Math `__add__(), __abs__(), __ceil__(), __sub__(), __mod__(), __mul__(), __round__(), __floordiv__()`
- Make vars private by adding '__' to the beginning of the variable name
- getters and setters are good, or you can make @property, @var_name.setter, etc functions
```
# Acts as a getter, but is used for class_name.color
@property
def color(self):
return self.__color
@color.setter
def color(self, value):
self.color = value
```
- Inheritance
- How to make inheritance in Python: `class Dog(Pet): # Dog inherits from Pet`
- Basic explanation of inheritance in OOP section.
- Arbitrary parameters
- Arbitrary num of parameters for a function/method
- Can use `*args` or `**kwargs` to get a tuple or dict with an arbitrary length
- Variable name doesn't actually matter those names are standard, just number of asterisks *. 1 for tuple, 2 for dict.
- Example:
```
def custom_sum(*args):
total = 0
for num in args:
total += num
return total
print(custom_sum(1, 2, 3, 4, 5, 6, 7, 8, 9))
```

View file

@ -0,0 +1,66 @@
from dog import Dog # Imports class from other python file (dog.py)
from cat import Cat
# dog1 and dog2 are variables holding reference to instance of Dog in heap
dog1 = Dog(color='blue')
dog2 = Dog(weight=15.7)
dog3 = Dog(breed='beagle', weight=15.7)
# Calls __str__()
print(dog1)
print(dog2)
# Calls __eq__()
print(dog1 == dog2)
# Also calls __eq__()
print(dog1 != dog2)
dog1.name = 'snow'
print(dog1.color)
dog1.name = 'light'
print(dog1.color)
# Is type "class '__main__.Dog'"
print(type(dog1), type(dog2))
# You can do these, but you shouldn't. It's not good for OOP
# Commenting out because it's a mess
# dog1.breath = 'bad'
# print(dog1.breath)
# for attribute in dir(dog1):
# print(f'{attribute}: {dog1.__getattribute__(attribute)}')
num1 = 42
num2 = 99
if num1 == num2:
print('Equal')
else:
print('Not equal')
print(dog2)
print(dog3)
print(dog2 == dog3)
dog1.do_something(item='newspaper')
# Cat
print()
cat1 = Cat(color='heliotrope')
print(cat1)
cat1.laser()
cat1.make_noise()
print()
# Other stuff
def get_full_name(*args): # Can be any name, as long as it starts with *.
full_name = ''
for name in args:
full_name += name + ' '
return full_name[:-1]
print(get_full_name('super', 'cali', 'fragilistic', 'expialidocious'))

50
Classes and OOP/dog.py Normal file
View file

@ -0,0 +1,50 @@
from pet import Pet
class Dog(Pet):
def __init__(self, name='Odie', color='brown', breed='poodle', weight=25.0): # self is equivalent of this
"""
Initializes instance of Dog class.
:param name: name of Dog
:param color: color of Dog
:param breed: breed of Dog
:param weight: weight of Dog
"""
super().__init__(name, color, breed)
# Can add __ before variable name to make it a private
# variable, so it can't be directly accessed. Only through methods.
self.__weight = weight
self.__bark()
@staticmethod
def __bark():
"""
woof
:return: None
"""
print('woof woof')
@property
def weight(self):
return self.__weight
@weight.setter
def weight(self, weight):
self.__weight = weight
def __str__(self):
return f'{self.name} {self.color} {self.breed} that weighs {self.__weight}.'
def __eq__(self, other):
if not isinstance(other, Dog):
raise TypeError
if super().color == other.color and super().breed == other.breed and self.__weight == other.__weight:
return True
return False
def do_something(self, **kwargs):
if 'item' in kwargs:
self.__bark()
print(f"Here's a {kwargs['item']}")
else:
print('*confusion*')

23
Classes and OOP/pet.py Normal file
View file

@ -0,0 +1,23 @@
class Pet:
def __init__(self, name, color, breed):
self.__name = name
self.__color = color
self.__breed = breed
# Can do this to make variables private, but look like public
@property
def name(self):
return self.__name
@name.setter
def name(self, name):
self.__name = name
@property
def color(self):
return self.__color
@property
def breed(self):
return self.__breed