Python. Object-oriented programming (OOP). Classes (en)

11.4.1.1 create classes and instances of classes
11.4.1.2 develop methods for the class
11.4.1.3 use special method __init__ to set default properties

Python. Object-oriented programming (OOP). Classes

All data in Python is an object. Numbers of all types, strings, lists, dictionaries, even functions, modules, and finally data types themselves are all objects!

An object in programming is an entity that has properties (attributes) and methods (operations on them).

Class is a data type that is created to describe complex objects. In Python, a class is a blueprint for a concrete object.

An instance is an object of a class that has its properties.

Attribute - a characteristic of each instance. An instance has all the attributes of a class.

A method is an action that an object can perform an instance of.

We should know!

All the data types we have studied are classes.

For example,

a = 5
print(type(a)) # <class 'int'>
x = {1:"one", 2: "two", 3: "three"}
print(type(x)) # <class 'dict'>

All values are objects.

For example,

5 is an instance of class 'int'
{1:"one", 2: "two", 3: "three"} is an instance of class 'dict'

Creating classes

You can create a class like this

class Fruit:
     pass

We have created a Fruit class. The class name is capitalized.

Now we can create instances of the Fruit class:

f1 = Fruit()  # f1 - an instance of the Fruit class
f2 = Fruit()  # f2 - an instance of the Fruit class

Object and class attributes are accessed using dot notation in Python.

Variables f1 and f2 contain references to two different objects - instances of the Fruit class, which can be endowed with different attributes (for example, name and weight):

f1.name = "orange"
f1.weight = 200 # now f1 is an orange weighing 200 grams

f2.name = 'banana'
f2.weight = 150 # now f2 is a banana weighing 150 grams

We can read attributes

f1.name = "orange"
f1.weight = 200
print(f1.name, f1.weight) # orange 200
f1.weight -= 10
print(f1.weight) # 190

If the attribute has not yet been created, then when reading such an attribute, an AttributeError will be output.

f3.name = "lime"
f3.color = "green"
print(f3.weight) # AttributeError

Class Methods

All functions within a class are called methods.

class Greeter:
    def hello(self): # hello is a method, self is an object greet
        print("Hello, World!")



greet = Greeter() # greet is an instance of Greeter class
greet.hello()  # output "Hello, world!"

When creating your own methods, pay attention to two points:

  • The method must be defined inside the class (indentation level added)
  • Methods always have at least one argument, and the first argument must be called self

The argument self is passed to the object that called this method. This is why self is often referred to as a context object.

Let's extend the previous program fragment and pass the arguments to the methods.

class Greeter:
    def hello(self):
        print("Hello, World!")
 
    def greeting(self, name):
        print(f"Hello, {name}!")
 
    def start_talking(self, name, weather_is_good):
        print(f"Hello, {name}!")
        if weather_is_good:
            print("Good weather, isn't it?")
        else:
            print("Disgusting weather, isn't it?")
 
 
greet = Greeter()
greet.hello()            # Hello, World!
greet.greeting("Halil")  # Hello, Halil!
 
greet.start_talking("Ruslan", True)  
# Hello, Ruslan!
# Good weather, isn't it?

Method __init__

The significance of the __init__ method is that, if such a method is defined in a class, the interpreter automatically calls it when creating each instance of that class to initialize the instance.

Example

class Fruit:
   def __init__(self):       # default values
      self.color = 'green'   # each object gets default color 'green'
      self.fruit = 'apple'   # each object gets default fruit 'apple'
      
   def info(self):           # method info output data about object
      return f'{self.color} {self.fruit}'


f1 = Fruit()
print(f1.info())              # green apple

The default values can be changed by creating methods on objects of the Fruit class.

class Fruit:
   def __init__(self):       # default values
      self.color = 'green'   # each object gets default color 'green'
      self.fruit = 'apple'   # each object gets default fruit 'apple'


   def color(self, color):
      self.color = color     # set new color for object of class Fruit


   def fruit(self, fruit):
      self.fruit = fruit     # set new fruit for object of class Fruit

   def info(self):

      return f'{self.color} {self.fruit}'

f1 = Fruit()
f1.color = 'red'
print(f1.info())  # red apple


Questions:

  1. Give definitions of the terms "class", "instance", "attribute", "method".
  2. Provide examples of classes and objects in Python.
  3.  

Exercises:

Ex 1. Fill the table

Ex 2. Fill the gaps

 


Tasks:

Task 1a. Create a Plate class, then create an instance of it called saucer with the attributes color="white" and size=100.
Get output "White saucer, size - 100"

Task 1b. Create a new AdvancePlate class that initializes the color and size attributes with the __init__() method. Also, the class must have a output() method that prints information about the plate in the form: "I am <color> a plate with a radius of <size> mm." 
Get output "I am violet a plate with a radius of 120 mm."

Task 2a. Create a class Car, then create an instance of it named midget_car (subcompact) with brand and length attributes with values “KIA” and 2600 respectively.
Get output "KIA is a model of car, length - 2600"

Task 2b. Create a new AdvanceCar class that initializes the brand and length attributes with the __init__() method. Also, the class should have an info() method that prints information about the car in the form: "I got a taxi <brand> with a length of <length> mm."
Get output "I got a taxi BMW with a length of 2800 mm."

Task 3. Write a program that asks for the user's number. If the number belongs to the range from -100 to 100, then the created instance belongs to the first class, otherwise, the created instance belongs to the second class. The class includes the __init__ method, which in the first-class calculates the square of a number, and in the second class, it multiplies by two.

Answer

1.   class One:
2.       def __init__(self,a):
3.           self.a = a ** 2
4.
5.   class Two:
6.       def __init__(self,a):
7.           self.a = a * 2
8.
9.   a = input ("Input number ")
10. a = int(a)
11. if -100 < a < 100:
12.     obj = One(a)
13. else:
14.     obj = Two(a)
15. print (obj.a)

Категория: Programming languages | Добавил: bzfar77 (11.03.2022)
Просмотров: 863 | Теги: Class, Method, Python, Function, init | Рейтинг: 4.8/4
Всего комментариев: 0
avatar