[python] Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

I just rewrote a working program into functions in a class and everything messed up.

First, in the __init__ section of the class I declared a bunch of variables with self.variable=something.

Should I be able to access/modify these variables in every function of the class by using self.variable in that function? In other words, by declaring self.variable I have made these variables, global variables in the scope of the class right?

If not, how do I handle self?

Second, how do I correctly pass arguments to the class?

Third, how do I call a function of the class outside of the class scope?

Fouth, how do I create an Instance of the class INITIALCLASS in another class OTHERCLASS, passing variables from OTHERCLASS to INITIALCLASS?

I want to call a function from OTHERCLASS with arguments from INITIALCLASS. What I've done so far is.

class OTHERCLASS():
    def __init__(self,variable1,variable2,variable3):
        self.variable1=variable1
        self.variable2=variable2
        self.variable3=variable3
    def someotherfunction(self):
        something=somecode(using self.variable3)
        self.variable2.append(something)
        print self.variable2
    def somemorefunctions(self):
        self.variable2.append(variable1)
        
class INITIALCLASS():
    def __init__(self):
        self.variable1=value1
        self.variable2=[]
        self.variable3=''
        self.DoIt=OTHERCLASS(variable1,variable2,variable3)

    def somefunction(self):
        variable3=Somecode
        #tried this
        self.DoIt.someotherfunctions()
        #and this
        DoIt.someotherfunctions()

I clearly didn't understand how to pass variables to classes or how to handle self, when to use it and when not. I probably also didn't understand how to properly create an instance of a class. In general I didn't understand the mechanics of classes so please help me and explain it to me like I have no idea (which I don't, it seems). Or point me to a thorough video, or readable tutorial.

All I find on the web is super simple examples, that didn't help me much. Or just very short definitions of classes and class methods instances etc.

I can send you my original code if you guys want, but its quite long.

This question is related to python class call parameter-passing instance-variables

The answer is


The whole point of a class is that you create an instance, and that instance encapsulates a set of data. So it's wrong to say that your variables are global within the scope of the class: say rather that an instance holds attributes, and that instance can refer to its own attributes in any of its code (via self.whatever). Similarly, any other code given an instance can use that instance to access the instance's attributes - ie instance.whatever.


So here is a simple example of how to use classes: Suppose you are a finance institute. You want your customer's accounts to be managed by a computer. So you need to model those accounts. That is where classes come in. Working with classes is called object oriented programming. With classes you model real world objects in your computer. So, what do we need to model a simple bank account? We need a variable that saves the balance and one that saves the customers name. Additionally, some methods to in- and decrease the balance. That could look like:

class bankaccount():
    def __init__(self, name, money):
        self.name = name
        self.money = money

    def earn_money(self, amount):
        self.money += amount

    def withdraw_money(self, amount):
        self.money -= amount

    def show_balance(self):
        print self.money

Now you have an abstract model of a simple account and its mechanism. The def __init__(self, name, money) is the classes' constructor. It builds up the object in memory. If you now want to open a new account you have to make an instance of your class. In order to do that, you have to call the constructor and pass the needed parameters. In Python a constructor is called by the classes's name:

spidermans_account = bankaccount("SpiderMan", 1000)

If Spiderman wants to buy M.J. a new ring he has to withdraw some money. He would call the withdraw method on his account:

spidermans_account.withdraw_money(100)

If he wants to see the balance he calls:

spidermans_account.show_balance()

The whole thing about classes is to model objects, their attributes and mechanisms. To create an object, instantiate it like in the example. Values are passed to classes with getter and setter methods like `earn_money()ยด. Those methods access your objects variables. If you want your class to store another object you have to define a variable for that object in the constructor.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to class

String method cannot be found in a main class method Class constructor type in typescript? ReactJS - Call One Component Method From Another Component How do I declare a model class in my Angular 2 component using TypeScript? When to use Interface and Model in TypeScript / Angular Swift Error: Editor placeholder in source file Declaring static constants in ES6 classes? Creating a static class with no instances In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Static vs class functions/variables in Swift classes?

Examples related to call

ReactJS - Call One Component Method From Another Component Call a Class From another class What does it mean to "call" a function in Python? How to make method call another one in classes? How to call a mysql stored procedure, with arguments, from command line? Submit form on pressing Enter with AngularJS Running bash script from within python javascript: get a function's variable's value within another function Passing variables, creating instances, self, The mechanics and usage of classes: need explanation Android Call an method from another class

Examples related to parameter-passing

How to pass parameter to a promise function Check number of arguments passed to a Bash script How to pass event as argument to an inline event handler in JavaScript? Passing Parameters JavaFX FXML Invoke a second script with arguments from a script How can I pass a member function where a free function is expected? Passing variables, creating instances, self, The mechanics and usage of classes: need explanation In Javascript/jQuery what does (e) mean? How to write a bash script that takes optional input arguments? Passing Objects By Reference or Value in C#

Examples related to instance-variables

What is an instance variable in Java? Ruby class instance variable vs. class variable Passing variables, creating instances, self, The mechanics and usage of classes: need explanation What does @@variable mean in Ruby? Ruby convert Object to Hash How do servlets work? Instantiation, sessions, shared variables and multithreading How to get instance variables in Python?