Learn about programming Classes and Objects in Python

Learn about programming Classes and Objects in Python: Objects are an encapsulation of variables and

functions into a single entity.

 

Objects get their variables and functions from classes. Classes are essentially a template to create your objects.

A very basic class would look something like this:

class MyClass:
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")

We’ll explain why you have to include that “self” as a parameter a little bit later. First, to assign the above class(template) to an

object you would do the following:


class MyClass:
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")

myobjectx = MyClass()

Now the variable “myobjectx” holds an object of the classMyClass” that contains the variable and the function

defined within the class called “MyClass“.

Accessing Object Variables

To access the variable inside of the newly created objectmyobjectx” you would do the following:

class MyClass:
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")

myobjectx = MyClass()

print(myobjectx.variable)

Trinket.io on-line Python compiler

So, for instance, the below would output the string “blah“:

class MyClass:
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")

myobjectx = MyClass()

print(myobjectx.variable)

Trinket.io on-line Python compiler

You can create multiple different objects that are of the same class(have the same variables and functions defined).

However, each object contains independent copies of the variables defined in the class. For instance, if we were to

define another object with the “MyClassclass and then change the string in the variable above:

class MyClass:
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")

myobjectx = MyClass()
myobjecty = MyClass()

myobjecty.variable = "yackity"

# Then print out both values
print(myobjectx.variable)
print(myobjecty.variable)

Trinket.io on-line Python compiler

Accessing Object Functions

To access a function inside of an object you use notation similar to accessing a variable:

class MyClass:
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")

myobjectx = MyClass()

myobjectx.function()

Accessing Object Functions

The above would print out the message, “This is a message inside the class.

Exercise

We have a class defined for vehicles. Create two new vehicles called car1 and car2. Set car1 to be a red convertible

worth $60,000.00 with a name of Fer, and car2 to be a blue van named Jump worth $10,000.00.

# this is the answer code.
# define the Vehicle class
class Vehicle:
    name = ""
    kind = "car"
    color = ""
    value = 100.00
    def description(self):
        desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)
        return desc_str

# your code goes here
car1 = Vehicle()
car1.name = "Fer"
car1.color = "red"
car1.kind = "convertible"
car1.value = 60000.00

car2 = Vehicle()
car2.name = "Jump"
car2.color = "blue"
car2.kind = "van"
car2.value = 10000.00

# test code
print(car1.description())
print(car2.description())

Trinket.io on-line Python compiler

Note: Running above unfinished-code will yield the following error:

Traceback (most recent call last):
File “script.py”, line 13, in
print(car1.description())
NameError: name ‘car1’ is not defined

OR

NameError: name ‘car1’ is not defined on line 13 in main.py

Learn about programming Classes and Objects in Python

Related Videos:

MiltonMarketing.com Related Videos.

Related Posts:

Adding Python Comments

Create a PayPal Donation Shortcode – WordPress

Using the class attribute

Using CSS classes

Python Online Compiler Code on the Go

Why Python is the cooler programming language

Methods of teaching programming

Python Online Compiler Code on the Go

The 14 most popular programming languages, according to a study of 100,000 developers

CSS HTML JAVASCRIPT Online Compiler Code on the go

Using CSS classes and the class attribute

Object-Oriented Programming (OOP)

Python Basic String Operations

Learn Python Lists

Python Serialization (JSON)

Learn List Comprehensions in Python Programming

Python Conditions

Python String Formatting

Python Conditions

Alice Teaches OOP (Glossary of useful terms)

Learn Code Introspection Python Programming

Learn Python Variables and Types

Python Basic Operators

Learn about Numpy Arrays in Python programming

Introduction to Python Programming Language

Learn Modules and Packages in Python programming

Learn Partial functions Python programming

Connected through code, Choose Your Platform!

About the Author: Bernard Aybout

In the land of bytes and bits, a father of three sits, With a heart for tech and coding kits, in IT he never quits. At Magna's door, he took his stance, in Canada's wide expanse, At Karmax Heavy Stamping - Cosma's dance, he gave his career a chance. With a passion deep for teaching code, to the young minds he showed, The path where digital seeds are sowed, in critical thinking mode. But alas, not all was bright and fair, at Magna's lair, oh despair, Harassment, intimidation, a chilling air, made the workplace hard to bear. Management's maze and morale's dip, made our hero's spirit flip, In a demoralizing grip, his well-being began to slip. So he bid adieu to Magna's scene, from the division not so serene, Yet in tech, his interest keen, continues to inspire and convene.