-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass_obj.py
84 lines (63 loc) · 1.67 KB
/
class_obj.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class Person:
pass
an_employee = Person()
print(type(an_employee))
class Person1:
species = "Homo sapiens"
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name}."
p1 = Person1("Alice", 25)
p2 =Person1("bob",32)
print(p1.greet())
print(p2.greet())
print(p1.species)
print(p2.species)
#private and public classes
print("")
print("This is a public and private classes")
class Person2:
def __init__(self, name, age):
self.name = name
self.__age = age
def get_age(self):
return self.__age # Accessing a private attribute
def set_age(self, age):
self.__age = age # Modifying a private attribute
pa = Person2("alice",25)
print(pa.get_age())
#inheritance
print("")
print("Example for inheritance")
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # calls the parent class constructor
self.breed = breed
def speak(self):
return f"{self.name} barks."
man = Animal("John")
print(man.speak())
#dog =Dog("Hunter")
#print(dog.speak())
do1 =Dog("Hunter", "Golden retriever")
print("This is from the super function",do1.speak())
#polymorphism
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "<eow!"
animals = [Dog(), Cat()]
for animals in animals:
print(animals.speak())