Posts: 38
Threads: 7
Joined: Jun 2020
Dear python users,
As a python newbie I started two months ago learning a bit of coding. By learning some topics of Python some questions came to my mind and I would like to ask here I someone could help me with this case(s). Now I am kind of assuming what the solution would be but I prefer doing it in the correct way avoiding frustrations in the future .
The query:
Inside class objects, should I use the SELF argument only in the __init__ def?
For example:
class CountFromBy:
def __init__(self, v: int=0, i: int=1):
self.val = v
self.incr = i
def increase(self):
self.val += self.incr
def __repr__(self) -> str:
return str(self.val) And what is the function of "v" and "i" in the __init__ object? Should it be better to used the same initials as "val" behind the self argument?
Hopefully the query description is understandable, please let me know if additional information is needed.
Like to hear!
Posts: 4,542
Threads: 69
Joined: Jan 2018
Aug-01-2020, 08:50 AM
(This post was last modified: Aug-01-2020, 08:56 AM by Gribouillis.)
Python_User Wrote:Inside class objects, should I use the SELF argument only in the __init__ def? Normally, you need to use the self argument in every method definition except when they are class methods or static methods (defined with the @classmethod and @staticmethod decorators). The self argument represents the object instance when the method is called. Actually, you could use another word than 'self' for this argument, but 'self' is traditional and that's what other python programmers expect.
The variables v, i in this __init__() method are the counter's initial value and increment. I don't think these are very good names because the __init__ function is the main public interface of the class. A user will call for example co = CountFromBy(5, 2) , so the meaning of these variables should be as explicit as possible. I would have used 'start' and 'step' because these names are used in the prototype of the well known range() function and every Python programmer will understand them immediately
class CountFromBy:
def __init__(self, start=0, step=1):
self.val = start
self.incr = step The annotations such as : int or -> str are not required in Python, although some people may consider that it makes a better documented code. It is a trend in today's Python to clutter the code with annotations. Personally, I don't want to sacrifice the 'informal' side of the Python language that makes it so flexible, so I prefer to avoid type annotations.
Posts: 38
Threads: 7
Joined: Jun 2020
Hi Gribouillis,
Thanks for your explanation.
Quote:The self argument represents the object instance when the method is called.
I don't understand this sentence, what do you mean with object instance? Because when you have multiple objects, how does the program know which self argument to invoke? Mostly I try to visualize definitions in my head, but with this self arguments it is difficult .
I tried to modified the code to run it once and increase the start value with 1, but I got a TypeError: 'int' object is not callable.
class CountFromBy:
def __init__(self, start=0, step=1):
self.start = start
self.step = step
def increase(self):
self.start += self.step
def __repr__(self) -> str:
return str(self.start)
x = CountFromBy(0, 1)
x.increase()
x.start()
Posts: 7,107
Threads: 122
Joined: Sep 2016
(Aug-01-2020, 09:46 AM)Python_User Wrote: I don't understand this sentence, what do you mean with object instance? Because when you have multiple objects, how does the program know which self argument to invoke? Mostly I try to visualize definitions in my head, but with this self arguments it is difficult Can run the class with some added comment and a class attribute.
class CountFromBy:
# class attribute or class varible both name are okay
reset = 0
def __init__(self, start=0, step=1):
# instance attributes
self.start = start
self.step = step
def increase(self):
'''I am method in Class CountFromBy'''
self.start += self.step
def __repr__(self) -> str:
return str(self.start) Run.
>>> # 0 and 1 is set as default parameters so no need to add same vaules
>>> # Only if start step need other vaules than 0 or 1,then put those in
>>> x = CountFromBy()
>>> x.start
0
>>> x.step
1
>>> x.increase ()
>>> x.start
1
>>> x.increase ()
>>> x.start
2
>>> x.increase ()
>>> x.start
3
# Step is always the same
>>> x.step
1
>>> # Call __repr__
>>> x
3
>>> # Reset
>>> x.start = x.reset
>>> # Now back to start
>>> x.start
0
>>> x.step
1
>>>
Posts: 38
Threads: 7
Joined: Jun 2020
Aug-02-2020, 08:04 AM
(This post was last modified: Aug-02-2020, 08:17 AM by Python_User.)
Thank you for the response Snippsat.
I am sorry but the following I don't understand:
# class attribute or class varible both name are okay Do you mean a class definition? I found it in the python (class) docs: https://docs.python.org/3/tutorial/classes.html
>>> x = CountFromBy()
>>> x.start From the code above, how does python know to run the __init__ object? As it has as well the self.start in the increase object.
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'User', 60000)
emp_1.fullname()
print(Employee.fullname(emp_1)) As well for this code above, how does the interpreter 'moves' through this code? How does python know to run the def __init__ if the code emp_1 = Employee('Corey', 'Schafer', 50000) invokes? Does the interpreter looks to the amount of arguments for each object?
Posts: 4,542
Threads: 69
Joined: Jan 2018
When you call the class name like a function, Python runs the __init__() method. When you call Employee() , you create an instance of the Employee class. This instance is initialized by calling automatically the __init__() method.
Posts: 38
Threads: 7
Joined: Jun 2020
I think the subject is getting clearer in my mind :).
So does this mean that you are limited to only one __init__ (function class)? Because when you make another function class python doesn't know where to refer right?
Posts: 7,107
Threads: 122
Joined: Sep 2016
Aug-02-2020, 10:08 AM
(This post was last modified: Aug-02-2020, 10:08 AM by snippsat.)
(Aug-02-2020, 08:04 AM)Python_User Wrote: Do you mean a class definition? I found it in the python (class) docs: https://docs.python.org/3/tutorial/classes.html No,i mean what reset = 0 is called.
class CountFromBy:
reset = 0 # class attribute
def __init__(self, start=0, step=1):
self.start = start # instance attributes They have different functionally a class attribute belongs to a class rather than a particular object.
class attribute is shared between all the objects of this class.
instance attribute belong to only one object,and are not shared between objects.
Python_User Wrote:From the code above, how does python know to run the __init__ object? As it has as well the self.start in the increase object. __init__() run automatically when create instance object x .
Then get also start=0 , step=1 set to these values,if was just start and step then need to give values when create a new instance objects.
If i give new arguments then the default values is no longer used.
>>> x = CountFromBy(10, 25)
>>> x.start
10
>>> x.step
25
>>> x.increase()
>>> x.start
35
>>> x.increase()
>>> x.start
60
>>> x.increase()
>>> x.start
85
Posts: 6,267
Threads: 16
Joined: Feb 2020
Actually Employee() calls a method named Employee.__new__(cls) to create a new INSTANCE of class Employee. Then it calls Employee.__init__(self) where "self" is the INSTANCE returned by the call to __new__. Both __new__ and __init__ are completely optional and Python automatically provides default methods for each that are inherited from the superclass. Most classes override the __init__ method, but overriding __new__ is fairly rare.
Stop using "function class". There is no such thing as a "function" class. A class in python is a collection of methods and class variables. A method looks a lot like a function, but it is associated with a class namespace instead of a module namespace. Because a class defines a namespace, each function and each variable can exist only once in the namespace. In this example __init__ gets defined twice. This does not generate any exceptions and the code runs fine, bit the second definition of __init__ quietly replaces the first. Though the class defines two methods, you can only access the last one that was defined. This is True of all "things" in the class namespace. The Doubleup namespace contains only one "__init__" and one "message" and one "classvar". Each instance has only one "punctuation".
class Doubleup:
classvar = 'Hello'
classvar = 'Goodbye'
def __init__(self):
self.punctuation = ','
self.punctuation = '!'
def __init__(self):
self.punctuation = ';'
self.punctuation = '?'
def message(self):
return f'Hello world{self.punctuation}'
def message(self):
return f'Goodbye world{self.punctuation}'
print(Doubleup().message()) Output: Goodbye world?
Instances of a class also have a namespace. Each instance of class Employee can have a different first name and a different last name because each instance of Employee has it's own namespace. When I give Bob a raise (Bob.pay *= 1.05), I am using the "pay" from the "Bob" namespace, and it does not affect the "pay" in the "Alice" namespace.
The more common way to say all of this is that each Class has its' own methods and class variables, and each instance of a class has its' own instance variables.
Posts: 38
Threads: 7
Joined: Jun 2020
Aug-02-2020, 03:02 PM
(This post was last modified: Aug-02-2020, 03:02 PM by Python_User.)
Ok, this is a bounce of information and difficult to understand.
class Doubleup:
classvar = 'Hello'
classvar = 'Goodbye'
def __init__(self):
self.punctuation = ','
self.punctuation = '!'
def __init__(self):
self.punctuation = ';'
self.punctuation = '?'
def message(self):
return f'Hello world{self.punctuation}'
def message(self):
return f'Goodbye world{self.punctuation}'
print(Doubleup().message()) From the code above:
- Why isn't the puntuaction defined as argument in the methods?
- What is the function of "f" in return f'Goodbye world{self.punctuation}' ?
- What is the curly brackets function in return f'Goodbye world{self.punctuation}' ?
- How knows python to refer to the question mark?? This is really difficult to understand for me at the moment...
Maybe the questions are dumb, but I am trying to understand it properly.
|