why do we pass self on all class methods? [duplicate] - python

This question already has answers here:
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed 1 year ago.
I know that some of you will think It's a stupid question but I will ask anyway.
why do we need to pass 'self' on all class methods can't we use it without passing it like this:
class Player:
def __init__(name):
self.name = name
def print_player_name():
print(self.name)

Try it. It won't work because self is not defined. The name "self" is just established, but you could name it whatever you want. It refers to the object of the class on which the method is called.

Yes, you can do it but you have to mention it as a static method. Self represents the instance of the class. In simple words, self represents the object on which it is being executed. When you create an object, all variables change their values based on different object of same class. Every class needs object as it's argument because for different object, different values are assigned

self represents object of class on which method is called you don't always need to name it self[standard convention] any valid variable name is allowed in python to do this but it should be first argument of non-classmethods and should be replace self as in if you run this python will work as expected :
class Player:
def __init__(hello, name):
hello.name = name
def print_player_name(hello):
print(hello.name)

It's very simple that's the official Python convention. In official docs we can read about it.
"Often, the first argument of a method is called self. This is nothing
more than a convention: the name self has absolutely no special
meaning to Python. Note, however, that by not following the convention
your code may be less readable to other Python programmers, and it is
also conceivable that a class browser program might be written that
relies upon such a convention."

Related

How does the "self" work in this python code [duplicate]

This question already has answers here:
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed last year.
Have two simple python codes, both are working. But no sure what is the "self" in there that makes the difference. When to use and when not to use "self"?
class car:
colour="red"
def method1():
print("method1")
myCar=car
myCar.method1()
class car:
colour="red"
def method1(self):
print("method1")
myCar=car()
myCar.method1()
In the first snippet, myCar refers to the class car, and method1 appears to be being used as a static method of that class.
In the second snippet, myCar refers to an instance of the class car, and method1 is an instance method -- the typical usage. Instance methods receive as a first argument the instance calling the method.
Conceptually, the difference is that in the second snippet you're referring to a car and in the first snippet you're referring to the concept of cars in general.

Can python class reference nonexistent variable and method? [duplicate]

This question already has answers here:
What is a mixin and why is it useful?
(18 answers)
Closed 2 years ago.
class SoftDeleteMixin(object):
deleted_at = Column(DateTime)
deleted = Column(types.SoftDeleteInteger, default=0)
def soft_delete(self, session):
"""Mark this object as deleted."""
self.deleted = self.id
self.deleted_at = timeutils.utcnow()
self.save(session=session)
In class SoftDeleteMixin method soft_delete, it references nonexistent self.id and self.save. Why can it do that in python?
Note: the focus is the class can reference nonexistent variable and method, not that it is a Mixin class.
If you instantiate a SoftDeleteMixin class and call the soft_delete method, you'll get an AttributeError.
If as you said in the comment those attributes are instantiated somewhere else, even in a child class, and you call soft_delete on a child class instance, it works because the attribute is there at the time the method is called.
To explain it in a simple way, python is an interpreted language, and except for syntax it does not perform too much checks on the whole file when executing the code, until that actual line is actually executed.
So yes, you could think it's a bad design but it is not, it's an accepted practice (see this question for more details) and it is allowed by the laguage. You can define methods which reference attributes not defined in a __init__ method or as class attributes or whatever. The important thing is that the istance has the attribute when the method is executed. It does not matter where or when the attribute is actually defined.
The word "mixin" in the class name means that this class is intended to be inherited by a class that already declares id and save(). If you try to use it by itself, it will cause errors.

Adding `__getattr__` method to an existing object instance [duplicate]

This question already has answers here:
Overriding special methods on an instance
(5 answers)
Closed 3 years ago.
I would like this to work:
import types
def new_getattr(self, *args, **kwargs):
return 2
class A:
def __init__(self):
pass
a = A()
a.__getattr__ = types.MethodType(new_getattr, a)
print(a.anything)
Right now, it throws AttributeError: A instance has no attribute 'anything'.
I tried different solutions proposed here and they work, but not for __getattr__.
If I do print(a.__getattr__('anything')), it actually prints 2; the problem is that my __getattr__ method is not called automatically when I do a.anything.
As a side note, in my actual implementation, I cannot modify the definition of the class A, nor can I type its name and do something like A.__getattr__ = ... (which would work) because I need this to be generic and independent of the class name.
Edit: I ended up doing it like this:
a.__class__.__getattr__ = new_getattr.
You can not - __dunder__ names are resolved on the type, not per-instance. Custom __getattr__ will need to be defined directly on A.
See Special method lookup section of the datamodel documentation, specifically:
For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary.
Note: if you only have a reference to an instance, not the class, it is still possible to monkeypatch the type by assigning a method onto the object returned by type(a). Be warned that this will affect all existing instances, not just the a instance.

Why is self a required parameter for a method? [duplicate]

This question already has answers here:
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed 4 years ago.
Let's say that I have a tiny code like this:
#!/usr/bin/env python3
class Dog():
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(self.name + " is now sitting.")
my_dog = Dog('willie',6)
my_dog.sit()
As I understand, the line my_dog = Dog('willie',6) creates an instance named my_dog. It calls the __init__ function, converts it internally to Dog.__init__(my_dog, willie, 6) and sets the my_dog.name and my_dog.age variables to willie and 6? Now when the my_dog.sit() is executed, then why does the method sit() require a self as a parameter? Is it because if there is another instance of the same class(for example, your_dog), then it knows to use your_dog.name instead of my_dog.name?
First of all, Python does not have the the offical syntax of instance variable.
When you call a method of an instance, Python will automatically insert the instance to the first argument.
So, you need pass at least one argument to the method. (It's can be self, this or anything)
"Self" signifies an instance of a class. Whenever a new instance of a class is created, "self" indicates that it will have its own variables that aren't shared with other instances. In your example, when an instance of school is made, that particular instance is referenced, it will have its own age and name variables, separate from any other school instance that may be created.
Basically, it's the opposite of a global variable. A "self" variable can only be directly used by a specific instance, rather than any thing else. If you want to use those variables, you have to clarify by using dot notation, e.g. school_one.age, school_two.name, etc.
Self refers to the instance which called the method. If a function does not require self, that implies the function does not need an instance of that certain class to call the method.

in python,what is the difference below, and which is better [duplicate]

This question already has answers here:
Difference between #staticmethod and #classmethod
(35 answers)
Closed 9 years ago.
I have written a code like this,and they are all works for me,but what is the difference? which is better?
class Demo1(object):
def __init__(self):
self.attr = self._make_attr()
def _make_attr(self):
#skip...
return attr
class Demo2(object):
def __init__(self):
self.attr = self._make_attr()
#staticmethod
def _make_attr():
#skip...
return attr
If both are working it means that inside make_attr you are not using self.
Making it a regular non-static method only makes sense if the code could logically depend on the instance and only incidentally doesn't depend on it in the current implementation (but for example it could depend on the instance in a class derived from this class).
When it comes to functionality, #staticmethod doesn't really matter. It's value is semantic - you are telling yourself, or other coders, that even though this function belongs to the namespace of the class, it isn't tied to any specific instance. This kind of tagging can be very useful when refactoring the code or when looking for bugs.
In either, attr is a local variable and does not depend on anything in the class. The results are the same. Marking it as static gives you the benefit of knowing this, and being able to access it directly, such as Demo2._make_attr() without having to create and instance of the class.
If you want it to acces the class variable, you would reference it as self.attr. But if you're doing this, then Demo2._make_attr() can no longer be static.

Categories