What is the name of functions defined under classes? [duplicate] - python

This question already has answers here:
What's the difference between a method and a function?
(41 answers)
Closed last year.
Below is a simple class, which is having one method/function in it
class Test():
def f(self):
return "function or method"
What should I call f() here - a method or a function?

From python official document's glossary:
method
A function which is defined inside a class body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self). See function and nested scope.

I'd say that is a method, since it is associated with the object of the class that it belongs to. I extracted the information from here.

Related

Why is the staticmethod decorator necessary? [duplicate]

This question already has answers here:
Does the #staticmethod decorator do anything?
(2 answers)
Closed 3 years ago.
Given that the following code runs without error, why is the staticmethod decorator necessary? What is it actually doing?
class Foo:
def say_hi(name):
print(f'Hello {name}.')
#staticmethod
def say_bye(name):
print(f'See ya later, {name}.')
my_name = 'Bar...t'
Foo.say_hi(my_name)
Foo.say_bye(my_name)
Static methods, much like class methods, are methods that are bound to a class rather than its object.
They do not require a class instance creation. So, they are not dependent on the state of the object.
The difference between a static method and a class method is:
Static method knows nothing about the class and just deals with the parameters.
Class method works with the class since its parameter is always the class itself.
https://www.programiz.com/python-programming/methods/built-in/staticmethod

Define class functions in different source files? [duplicate]

This question already has answers here:
Define a method outside of class definition?
(5 answers)
Closed 4 years ago.
Is it possible (preserving all the class functionality) to write the class functions in separate files?
Below is an example:
TestClass.py:
class MyClass():
def __init__(self, param1=1, param2=2, param3=3):
self.param1, self.param2, self.param3 =param1, param2, param3,
def ClassFun1(self, param1=2):
return param1**2/self.param2
TestClass2.py:
def ClassFun2(self, param1=3):
return param1*3/self.param2
Next, following this answer, I compile both files (I am too lazy to use import), create a class variable and try to use ClassFun2:
x=MyClass()
x.myMethod=ClassFun2
x.myMethod(2)
As a result, I get an error, since self in ClassFun2 is treated as a parameter, rather than class itself:
AttributeError: 'int' object has no attribute 'param2'
Is it possible to split class definition into several source files? It is possible in C++ and this is actually very convenient when working as a team.
The variable x is an object of the class, not the class itself. You need to do:
x = MyClass
x.myMethod = ClassFun2
Notice that I didn't put () after MyClass. That returns the class itself, it doesn't return an instance of the class.
Then you need to create an instance to execute the method:
y = MyClass()
y.myMethod(2)

When to use keyword "self" in Python [duplicate]

This question already has answers here:
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed 5 years ago.
How to use "self" keyword regarding variables? It seems that you can set a class variable inside of __init__ constructor by using "self" prefix???
self is just a name used as a convention to refer to the instance on which methods are bound. Bound methods are always called with the instance as first argument, and you can name that variable anything.
By using self in an instance method, we set instance variables and not class ones. Different programming languages provide mechanisms to access the instance some use implicit this objects, some implicitly call all methods on the instance, and Python explicitly uses passes the instance as the first variable.

Static method overloading [duplicate]

This question already has answers here:
Overriding a static method in python
(3 answers)
Closed 6 years ago.
Suppose we declare a static method with same name in different classes. Is it possible?
If it is, then how and which function will be called?
class abc:
#staticmethod
def xyz():
print 'class_abc'
class abc1:
#staticmethod
def xyz():
print 'class_abc1'
class abc2:
#staticmethod
def xyz():
print 'class_abc2'
So what's the output and how we can call different functions of different classes?
You are having three classes with xyz() function in each class. But there is no relationship in these classes as they are not inheriting each other. So the answer is simple: xyz() will be called of the class which is calling the method.
For example: abc.xyz() will call the xyz() function of abc class. Similarly you can make call to ab1 and abc2's function as: abc1.xyz() and abc2.xyz().
You seem to be misunderstanding things. Classes introduce a separate namespace for themselves so, it is completely possible to create functions with the same name in different classes. These functions are not related in any other way other than their similar name.
Running <classname>.xyz() simply calls xyz() and prints the corresponding message.
Even if there was a relationship between the class, i.e a sub-classing relationship of the form:
class abc:
#staticmethod
def xyz():
print 'class_abc'
class abc1(abc):
#staticmethod
def xyz():
print 'class_abc1'
class abc2(abc1):
#staticmethod
def xyz():
print 'class_abc2'
The most recent definition of xyz will override previously existing entries for it and the effect would be the same, that is abc2.xyz() would print class_abc2, abc1.xyz() prints class_abc1 and so on.
Also, do note, you're using Python 2.x but aren't actually inheriting from object. This won't create a class in the sense most people are aware with today, take a look at What is the difference between old style and new style classes in Python? to get a better idea of what this entails.
Suppose we declare a static method with same name in different is it possible?
Yes
If it is possible then how and which function will be called.?
It's possible because classes have their own scope. Python treats each static method in your example differently. And even if your classes where related, such as in #Jim Fasarakis-Hilliard example, the current method would override the last method.
Each method will be called uniquely because each class is unrelated in your example(except for all of the classes being of type class).

Clarification regarding self [duplicate]

This question already has answers here:
When is "self" required?
(3 answers)
Closed 8 years ago.
In methods when is it necessary to use notation like self.variable_name? For instance, I know that in the constructor method it needs to be like
class A(object):
def __init__(self, name):
self.name = name
in order to give it an instance variable. However, what about in other methods? When do I need to put self in front of a variable name and when is it okay to just use a variable name?
You must always put a self as the first argument of an instance method. This is what you use to access the instance variables.
It is similar to this in other languages, but different in that it is required whereas other languages will often have instance variables in scope.
Whenever you are wanting to access attributes of the particular object of type A. For example:
def get_name(self): # here, whenever this method is called, it expects 'self'.
return self.name
When calling this method outside of the class scope, python has self passed implicitly.
example = A('d_rez')
example.get_name() # no arguments are passed, but self is passed implicitly to
# have access to all its attributes!
So to answer your question: You need to pass self whenever you define a method inside a class, and this is usually because there are some attributes involved. Otherwise, it could just be a static function defined outside the class if it doesn't pertain to a particular instance of class A.

Categories

Resources