Jump to content

Classes

From Slow Like Wiki
Revision as of 13:16, 15 April 2024 by Rob (talk | contribs) (Created page with "== Basic Class == <syntaxhighlight lang="python" line> class Cat: # Use capital letter for class name """Basic class with simple attributes and methods """ def __init__(self, name, age): # Special method to create an instance """Initialize attributes""" self.name = name self.age = age def eat(self): # Method defined in class """Sim...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Basic Class


class Cat:                                          # Use capital letter for class name
    """Basic class with simple attributes 
    and methods """

    def __init__(self, name, age):                  # Special method to create an instance
        """Initialize attributes"""
        self.name = name
        self.age = age

    def eat(self):                                  # Method defined in class
        """Simulate cat eating"""
        print(f"{self.name} is eating.")

    def sleep(self):
        """Simulate cat sleeping"""
        print(f"{self.name} is sleeping.")

my_cat = Cat('Sushi', 4)                            # Create one instance
your_cat = Cat('Basil', 3)                          # Create another
print(f"My cat is called {my_cat.name} \
and your cat is called {your_cat.name}.") 
my_cat.eat()                                        # Call method
your_cat.sleep()