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.
Related
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."
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.
This question already has answers here:
how to get derived class name from base class
(7 answers)
Closed 5 years ago.
So I have my base class:
class Foo():
pass
I'm never going to instantiate this class - I just want it as a custom namespace. One of the things I want from it is its name:
>>> Foo.__name__
'Foo'
But I want to change the interface to this, so that there's no underscores. Getting the name of the class from the class object is going to happen a lot, so it should be cleaner:
class Foo:
def name():
return Foo.__name__
This works great! Oh, except I have the name "Foo" hard coded. I might as well just have it return a string. That's not good enough, because I need to inherit this adjustment:
class Bar(Foo):
pass
>>> Bar.name()
'Foo'
No bueno.
Basically, I need a class function that returns the name of the class, and which will still work when inherited. I can't use self because I'm not making instances. Is there anything which will achieve a similar result? Do functions know about the namespace they are called from? If I really need to use objects I will, but for my purposes that will be uglier than a simple class hierarchy.
EDIT: I do not not believe this question is the same as the one it has been linked with. The solutions provided to the other question - mainly invoking the .__class__ attribute - would not work as an answer to this question because in my example I explicitly avoid instantiating objects. Also, the best answer provided here (using the #classmethod decorator to get the class object as a "self"-esque arg) appears nowhere in the linked alternative. Also, I believe my question to be framed in a clearer and more basic way than its purported duplicate. The same goes for the answer chosen.
Just make it a class method with #classmethod and return the name of the class that's passed in:
class Foo:
#classmethod
def name(cls):
return cls.__name__
class Bar(Foo): pass
This returns the correct name in each case:
>>> Foo.name()
'Foo'
>>> Bar.name()
'Bar'
This question already has answers here:
Nested Python class needs to access variable in enclosing class
(6 answers)
Closed 8 years ago.
I'm trying to assign a variable in my inner class with the variable on the outer class.
class OUTER(QtGui.QWidget):
def __init__(self):
super (OUTER, self).__init__()
self.initUI()
def number (self):
self.out = 50
...
class INNER(QtGui.QLCDNumber)
in = OUTER.out #error: NameError: name 'OUTER' is not defined
#pyqtSlot()
def some_func(self):
self.display(self.in)
I'm getting an error
NameError: name 'OUTER' is not defined.
Is there any way to fix this?
You can't do this.
OUTER is not defined until the entire outer class declaration is finished. Class bodies are executable code; they are executed at definition time. When the body is defined, it is allocated to the name, but until then the name does not exist.
That is one of the reasons why nesting classes is rarely a good idea in Python. The inner class does not get any special access to the outer class, so there isn't really any reason to nest them at all.
Plus, I've just noticed that you are trying to refer to an instance variable via a class. That can't ever work. OUTER.out does not exist, only instances of OUTER have an out attribute. (What would the value of OUTER.out even be?)
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.