How to create class in python

Python Classes and Objects

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a «blueprint» for creating objects.

Create a Class

To create a class, use the keyword class :

Example

Create a class named MyClass, with a property named x:

Create Object

Now we can use the class named MyClass to create objects:

Example

Create an object named p1, and print the value of x:

The __init__() Function

The examples above are classes and objects in their simplest form, and are not really useful in real life applications.

To understand the meaning of classes we have to understand the built-in __init__() function.

All classes have a function called __init__(), which is always executed when the class is being initiated.

Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created:

Example

Create a class named Person, use the __init__() function to assign values for name and age:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

Note: The __init__() function is called automatically every time the class is being used to create a new object.

The __str__() Function

The __str__() function controls what should be returned when the class object is represented as a string.

If the __str__() function is not set, the string representation of the object is returned:

Example

The string representation of an object WITHOUT the __str__() function:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

Example

The string representation of an object WITH the __str__() function:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

Object Methods

Objects can also contain methods. Methods in objects are functions that belong to the object.

Let us create a method in the Person class:

Example

Insert a function that prints a greeting, and execute it on the p1 object:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print(«Hello my name is » + self.name)

p1 = Person(«John», 36)
p1.myfunc()

Note: The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.

The self Parameter

The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.

It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class:

Example

Use the words mysillyobject and abc instead of self:

class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age

def myfunc(abc):
print(«Hello my name is » + abc.name)

p1 = Person(«John», 36)
p1.myfunc()

Modify Object Properties

You can modify properties on objects like this:

Example

Delete Object Properties

You can delete properties on objects by using the del keyword:

Example

Delete the age property from the p1 object:

Delete Objects

You can delete objects by using the del keyword:

Example

The pass Statement

class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error.

Источник

Python Class: A Complete Guide (Beginner Friendly)

Python is an object-oriented programming language. It means almost everything is an object. When becoming a Python developer, it’s crucial to learn what is a Python class and how to use it to create those objects.

A Python class is a blueprint for creating objects.

For example, here is a simple class Person , that has an attribute name :

Now you can create a Person object from the class by:

An object is also known as an instance of a class. The process of creating objects from a class is called instantiation.

You can use a class to instantiate different objects that all represent the class. For example, you can create multiple persons with different names.

How to Crete a Class in Python

To create a new Python class, use the class keyword.

Here is the syntax for defining a class in Python:

Now, every piece of code you write into this block belongs to that class.

For now, we are going to pass the implementation of the class, as we will return to it later on.

How to Use a Python Class

In the previous section, you learned the syntax for creating a class in Python. But how can you use this class?

The answer is you can create, or more formally, instantiate objects of the class.

Creating an instance of the above ExampleClass looks like this:

Now obj is a Python object that represents the ExampleClass . It thus has all the behavior described in the class. However, now the ExampleClass is empty, thus you can not do much with its representative objects.

In the next section, we are going to learn how to associate properties and behavior with the class. This way you can put your class into use.

Attributes and Methods in a Python Class

A bare class is not much of use. To benefit from using classes, you need to associate some behavior with them.

For example, a Person class could store info about the person and a method that introduces it.

To associate properties and behavior to a class, you need to create attributes and methods in the class.

Let’s first have a look at how to create class attributes in Python.

Attributes in a Class

Attributes in classes are properties that are present in the class and its objects. For example, a Fruit class could have a color attribute.

To create attributes in a class, declare them as variables in the class.

For example, let’s create a Fruit class with a color attribute:

class Fruit: color = "Yellow"

(Keep in mind you can add as many attributes to your class as you want.)

If you now instantiate a Fruit object based on the above Fruit class, you can access its color property using the dot notation.

For example, let’s create a Fruit object called some_fruit and display its color by printing it into the console:

some_fruit = Fruit() print(some_fruit.color)

Now, the color of some_fruit is «Yellow» because that’s what you defined in the class. But you can change it for this particular object if you wish to.

For instance, let’s turn some_fruit to red:

some_fruit.color = "Red" print(some_fruit.color)

This change in color does not affect the Fruit class. Instead, it only changes the object, as you can see.

Now that you understand what class attributes are in Python, let’s take a look at methods in classes.

Methods in a Python Class

A function inside a class is known as a method. A method assigns behavior to the class.

Usually, a method uses the attributes (or the other methods) of the class to perform some useful task. For example, a Weight class could have a kilograms attribute. In addition, it can have a to_pounds() method, that converts the kilograms to pounds.

To create a method for your class in Python, you need to define a function in it.

As mentioned, the method needs to access the attributes of the class. To do it, the method has to accept an argument that represents the class itself.

Let’s put it all together in a form of a simple example:

Let’s create a Person class and define an introduce() method to it. This makes it possible for each Person object to introduce themselves by calling person.introduce() :

class Person: name = "Sophie" def introduce(self): print("Hi, I'm", self.name)

If you now look at the introduce() method, you can see it takes one argument called self . This is there because as mentioned earlier, the class needs to be able to access its own attributes to use them. In this case, the person needs to know the name of itself.

Now you can create a person objects and make them introduce themselves using the introduce() method.

worker = Person() worker.name = "Jack" worker.introduce()

Python class instances with different names

Wonderful! You know the basics of defining a class and creating objects that contain attributes and some useful behavior.

But in the above example, the name of a Person is always Sophie to begin with. When you create a person object, you need to separately change its name if you want to. Even though it works, it is not practical.

A better for instantiating objects would be to directly give them a name upon creation:

Instead of first creating an object and then changing its name on the next line:

dude = Person() dude.name = "Jack"

To do this, you need to understand class initialization and instance variables. These give you the power to instantiate objects with unique attributes instead of separately modifying each object.

Class Initialization in Python

As you saw in the previous section, creating a person object with a unique name is only possible this way:

dude = Person() dude.name = "Jack"

But what you actually want is to be able to do this instead:

This is possible and it is called class initialization.

To enable class initialization, you need to define a special method into your class. This method is known as a constructor or initializer and is defined with def __init__(self): .

Every class can be provided with the __init__() method. This special method runs whenever you create an object.

You can use the __init__() method to assign initial values to the object (or run other useful operations when an object is created).

The __init__() method is also known as the constructor method of the class.

In the Person class example, all the Person objects have the same name “Sophie” .

Python class instances with the same properties

But our goal is to be able to create persons with unique names like this:

worker = Person("Jack") assistant = Person("Charlie") manager = Person("Sofie")

To make it possible, implement the __init__() method in the Person class:

class Person: def __init__(self, person_name): self.name = person_name

Now, let’s test the Person class by instantiating person objects:

worker = Person("Jack") assistant = Person("Charlie") manager = Person("Sofie")
print(worker.name, assistant.name, manager.name)

Let’s inspect the code of the Person class to understand what is going on:

  • The __init__() method accepts two parameters: self and person_name
  • self refers to the Person instance itself. This parameter has to be the first argument of any method in the class. Otherwise, the class does not know how to access its properties.
  • person_name is the name input that represents the name you give to a new person object.
  • The last line self.name = person_name means “Assign the input person_name as the name of this person object.”

self.name is an example of an instance variable. This means that self.name is an instance-specific (or object-specific) variable. You can create Person objects each with a different name .

To Recap

Initialization makes it possible to assign values to an object upon creation. The __init__() method is responsible for the initialization process. The method runs whenever you create a new object to set it up. This way you can for example give a name to your object when creating it.

Conclusion

In Python, a class is an outline for creating objects.

A Python class can store attributes and methods. These define the behavior of the class.

Also, you can initialize objects by implementing the __init__() method in the class. This way you can create objects with unique values, also known as instance variables without having to modify them separately.

Thanks for reading. Happy coding!

Источник

Читайте также:  Поиск html кода php
Оцените статью