Python Method/Function - python

hi I just started teaching myself Python couple of days ago and right now got really confused about the usage of"." when calling Method/Function. when def is created within a class, it would be a"Method", where you would have to call it by typing "the name of the instance "."the name of the method"()
this makes sense because the first argument "self" is connected to the instance created.
however, when using Numpy I encountered a "function" np.random.rand()
How is this possible? this function already has two objectives(np,random). how can this be created when using only two elements "package(class)" and "moduel(def)". what does "." mean in this function? Thank you

The rand() function you want to use is part of the random module of the numpy package.
Without going deep into packages and namespace structure, here is a quick example of why this matters:
If you import packages, you load additional functions, classes and structures into your namespace. But maybe you want to use math and numpy, which both have a sin()-function:
import numpy as np
import math
a = np.sin()
b = math.sin()
a and b are not the same function, but have the same name, so it is useful to call them by the name of the containing package.
The same applies for the standard sum() and the np.sum().
If you explicitly want to use the rand() function without calling it by the full name, you can do that by
from numpy.random import rand

In Python, just like in Java, it is possible to define classes. Classes are representations of a concept that you want to include in your code. For example, imagine that you create a person class where you want to store name and height. A very simple implementation could be:
class person:
def __init__(self, name, height):
self.name = name
self.height = height
def grow_up(self, cm):
self.height += cm
return
In this case, __init__(self, name, height) and grow_up(self, cm) are methods: they are defined inside a class and they take as a first argument self, that is, the instance of the class itself. An instance of the class is, in this example, any single person that you associate with this class. For example
a = person("John", 120)
Now, a is an instance of the class person and the arguments "John" and 120 are passed to the special initializer method __init__. If you call a.height you will obtain 120. (Should you use a getter for that? Maybe yes, maybe no, but that's not the point of your question)
Using the method grow_up is as simple as typing
a.grow_up(10)
Calling a.height again you now obtain 130.
A function is not defined inside a class, therefore, it can't have a self variable. It is similarly defined with a def command, however, which can generate some confusion. To make things even more ambiguous for beginners, python defines modules and packages. A module is a collection of functions stored in a single file, and a package is a directory containing one or more such modules. The standard way of navigating the namespace is the same as for class functions: using a dot (.) to separate packages, modules, and functions, going from the outermost to the innermost level.

Package np, package random and function rand effectively are python objects. Objects can have attributes and you can access them with dot notation and this chain (obj.attr1.attr2...attrN) can be long.
So in your example you just access attribute rand of attribute random of package np, and since rand is a callable object, you call it with rand().

When you are using numpy or any other packages it will not create a object.
For example:
import numpy as np
It will only download this package and you can use it.
In other words you can say numpy is a folder and it contain subfolders and scripts. Random is a subfolder. Rand() is a function.
Conclusion:
np.random.rand()
You are using dots to define a path for this function.
Here is a code for numpy package: https://github.com/numpy/numpy/tree/master/numpy

Related

How do I take functions that I already made to run a program and put them under a class?

I am making a contact list system for a class project and used tkinter to make my gui and sqlite3 for the database. I made a bunch of methods that have basically solved the problem but I noticed the question paper says that the functions need to be in a class. How do I put these functions under a class without messing everything up. I am using python3.
A function in a module is similar to a static method in a class. Without knowing any of your app's specifics:
If you have a function that does what you want
def f():
return 'g'
and you want to encapsulate it in a class
class Q:
pass
just assign it as a static method to that class
Q.f = staticmethod(f)
Whenever you need to use that function you have to call it via the class
>>> Q.f()
g
This is similar to what happens when you import a module that has functions - you import the module and call the functions using the module name (the functions are module attributes) - modulename.func().
I really have no idea how this fits with your need or what any downsides might be.

Do I add my functions for a module into a class?

I'm working on a function library/module for a project. I was wondering, to use it in another file as a module, do I need to put it in a class? I've tried adding my module to other files, but it doesn't work. Also, a lot of other built-in modules are in a class. Should I put it in a class or not? I'm also looking for an objective answer and not if it's a common practice or not.
You can put it in a class or let it outside a class. It depends on the use of this function.
e.g.:
class MyClass:
#staticmethod
def function(arguments):
# Your code
In order to import it you will have to use this:
from name_of_the_file import name_of_the_class
In the file you will have to use name_of_the_class.name_of_the_function().
e.g.:
MyClass.function(arguments)
If you define the function outside a class:
from name_of_the_file import name_of_the_function
In general, you don't need to put functions in a class. For example, functools.wraps() is a function.
However, you haven't mentioned the actual problem you're having, so this general answer is probably not very helpful.

How to convert a "custom class"-based singleton object programmatically into a python module?

I would like to convert a singleton-object programmatically into a Python module so that I can use the methods of this singleton-object directly by importing them via the module instead of accessing them as object attributes. By "programmatically" I mean that I do not want to have to copy-paste the class methods explicitly into a module file. I need some sort of a workaround that allows me to import the object methods into to global scope of another module.
I would really appreciate if someone could help me on this one.
Here is a basic example that should illustrate my problem:
mymodule.py
class MyClass:
"""This is my custom class"""
def my_method(self):
return "myValue"
singleton = MyClass()
main_as_is.py
from mymodule import MyClass
myobject = MyClass()
print(myobject.my_method())
main_to_be.py
from mymodule import my_method # or from mymodule.singleton import my_method
print(my_method())
You can use the same strategy that the standard random module uses. All the functions in that module are actually methods of a "private" instance of the Random class. That's convenient for most common uses of the module, although sometimes it's useful to create your own instances of Random so that you can have multiple independent random streams.
I've adapted your code to illustrate that technique. I named the class and its instance with a single leading underscore, since that's the usual convention in Python to signify a private name, but bear in mind it's simply a convention, Python doesn't do anything to enforce this privacy.
mymodule.py
class _MyClass:
""" This is my custom class """
def my_method(self):
return "myValue"
_myclass = _MyClass()
my_method = _myclass.my_method
main_to_be.py
from mymodule import my_method
print(my_method())
output
myValue
BTW, the from mymodule import method1, method2 syntax is ok if you only import a small number of names, or it's clear from the name which module it's from (like math module functions and constants), and you don't import from many modules. Otherwise it's better to use this sort of syntax
import mymodule as mm
# Call a method from the module
mm.method1()
That way it's obvious which names are local, and which ones are imported and where they're imported from. Sure, it's a little more typing, but it makes the code a whole lot more readable. And it eliminates the possibility of name collisions.
FWIW, here's a way to automate adding all of the _myclass methods without explicitly listing them (but remember "explicit is better than implicit"). At the end of "mymodule.py", in place of my_method = _myclass.my_method, add this:
globals().update({k: getattr(_myclass, k) for k in _MyClass.__dict__
if not k.startswith('__')})
I'm not comfortable with recommending this, since it directly injects items into the globals() dict. Note that that code will add all class attributes, not just methods.
In your question you talk about singleton objects. We don't normally use singletons in Python, and many programmers in various OOP languages consider them to be an anti-pattern. See https://stackoverflow.com/questions/12755539/why-is-singleton-considered-an-anti-pattern for details. For this application there is absolutely no need at all to use a singleton. If you only want a single instance of _MyClass then simply don't create another instance of it, just use the instance that mymodule creates for you. But if your boss insists that you must use a singleton, please see the example code here.

list methods with same name in a Python package

I am writing a Python package in which I have different Classes with a common method called map. That method always returns a function and is intended to be use inside a method of another package. Is there a way to lists all methods that are called map inside my package?
You're going to need to dip into a bit of reflection on this one. The steps you need are to load a reference a given module, grab the list of classes and then examine each class to make sure it has the method map:
import sys, inspect
def map_classes(module_name):
for name, obj in inspect.getmembers(sys.modules[module_name]):
if inspect.isclass(obj):
try:
if callable(getattr(obj, 'map')):
yield name
except AttributeError:
pass
This method will return a generator of all names of all classes within a module that have a map method. Note, if they have a map attribute, it will not return the name of the class.
You don't need the inspect package. Everything you need is built-in.
>>> import numpy as np
>>> for name, obj in np.__dict__.items():
... if hasattr(obj,"tolist"):
... print name, obj

How to make a python class not exposed to the outside?

I'm relatively new to Python.
When I did C/C++ programming, I used the internal classes quite often. For example, in some_file.cc, we may implement a class in the anonymous namespace to prevent it from being used outside. This is useful as a helper class specific to that file.
Then, how we can do a similar thing in Python?
class MyClassOuter:
def __init__(self,...):
class MyClassInner:
def __init__(self,...):
pass
self.my_class = MyClassInner(..)
would only have MyClassInner available inside the __init__ function of MyClassOuter
likewise you could put it inside a function
def my_class_factory(arg1,arg2,...):
class MyClass:
def __init__(self,arg1,arg2,...):
print "OK??"
return MyClass(arg1,arg2,...)
Python code doesn't have any such equivalent for an anonymous namespace, or static linkage for functions. There are a few ways you can get what you're looking for
Prefix with _. Names beginning with an underscore are understood
to be for internal use to that python file and are not exported by
from * imports. it's as simple as class _MyClass.
Use __all__: If a python file contains a list a list of strings
named __all__, the functions and classes named within are
understood to be local to that python file and are not exported by
from *.
Use local classes/functions. This would be done the same way you've
done so with C++ classes.
None these gets exactly what you want, but privacy and restricting in this way are just not part of the language (much like how there's no private data member equivalent). Pydoc is also well aware of these conventions and will provide informative documentation for the intended-to-be-public functions and classes.

Categories