01Define a class
main.py
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says woof!"
d = Dog("Rex")
print(d.bark())Output
Rex says woof!
Classes, inheritance, and special methods.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says woof!"
d = Dog("Rex")
print(d.bark())Rex says woof!
class Animal:
def speak(self):
return "..."
class Cat(Animal):
def speak(self):
return "Meow"
print(Cat().speak())Meow
class Counter:
count = 0
def __init__(self):
Counter.count += 1
a = Counter()
b = Counter()
c = Counter()
print(Counter.count)3
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __str__(self):
return f"({self.x}, {self.y})"
p = Point(3, 4)
print(p)(3, 4)
class Math:
@staticmethod
def add(a, b):
return a + b
@classmethod
def name(cls):
return cls.__name__
print(Math.add(3, 4))
print(Math.name())7 Math