This is just a way to declare a and b as equal to c.
>>> c=2
>>> a=b=c
>>> a
2
>>> b
2
>>> c
2
So you can use as much as you want:
>>> i=7
>>> a=b=c=d=e=f=g=h=i
You can read more in Multiple Assignment from this Python tutorial.
Python allows you to assign a single value to several variables simultaneously. For example:
a = b = c = 1
Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example:
a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b, and one string object with the value "john" is assigned to the variable c.
There is also another fancy thing! You can swap values like this: a,b=b,a:
>>> a=2
>>> b=5
>>> a,b=b,a
>>> a
5
>>> b
2
Answer from fedorqui on Stack OverflowThis is just a way to declare a and b as equal to c.
>>> c=2
>>> a=b=c
>>> a
2
>>> b
2
>>> c
2
So you can use as much as you want:
>>> i=7
>>> a=b=c=d=e=f=g=h=i
You can read more in Multiple Assignment from this Python tutorial.
Python allows you to assign a single value to several variables simultaneously. For example:
a = b = c = 1
Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example:
a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b, and one string object with the value "john" is assigned to the variable c.
There is also another fancy thing! You can swap values like this: a,b=b,a:
>>> a=2
>>> b=5
>>> a,b=b,a
>>> a
5
>>> b
2
python support multi variable assignment at a time called multiassignment.
In [188]: a = b = c = d = 4
In [189]: a
Out[189]: 4
In [190]: b
Out[190]: 4
In [191]: c
Out[191]: 4
In [192]: d
Out[192]: 4
In [193]: a = 2
In [194]: b = 2
is same as for immutable object
In [195]: a, b = 2 #int is a immutable object like `tuple`, `str`
while this is not to be mean for mutable object like list, dictionary
read about mutable and immutable
Videos
I am being asked to maintain code that subclasses from abc.ABC. I have read the python documentation, the associated PEP, and even visited pymotw. I do not understand what abstract classes give you.
If I have class A and then I derive subclass B from it wouldn't issubclass(B,A) still be true?
This is documented here.
Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.
And, as an example,
Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).
Python chains relational operators "naturally". Note that Python's relational operators include in and is (and their negatives), which can lead to some surprising results when mixing them with the symbolic relational operators.
s.accept() returns a tuple of two values : (host, port).
Therefore,
conn, address = s.accept()
is (apart that accept() is called twice) the same as
conn, address = s.accept()[0], s.accept()[1]
when receiving a tuple you can unpack(or "split") it into its members by using this syntax:
member1, member2, member3 = tuple
or
member1, member2 member3 = (member1, member2 member3)
in your case you are receiving a tuple of the form (connection, address), so to unpack it into two variables you write:
conn, address = s.accept()
It's equivalent to this:
returned_tuple = s.accept()
conn, address = returned_tuple
SubQuery is an abstract base class (per the abc module) with one or more abstract methods that you did not override. By adding ABC to the list of base classes, you defined ValueSum itself to be an abstract base class. That means you aren't forced to override the methods, but it also means you cannot instantiate ValueSum itself.
PyCharm is warning you ahead of time that you need to implement the abstract methods inherited from SubQuery; if you don't, you would get an error from Python when you actually tried to instantiate ValueSum.
As to what inheriting from ABC does, the answer is... not much. It's a convenience for setting the metaclass. The following are equivalent:
class Foo(metaclass=abc.ABCMeta):
...
and
class Foo(abc.ABC):
...
The metaclass modifies __new__ so that every attempt to create an instance of your class checks that the class has implemented all methods decorated with @abstractmethod in a parent class.
The 'Abstract Base classes" or abc.ABC is a helper class
https://docs.python.org/3/library/abc.html
Here's a snippet of why they exist:
The collections module has some concrete classes that derive from ABCs; these can, of course, be further derived. In addition, the
collections.abcsubmodule has some ABCs that can be used to test whether a class or instance provides a particular interface, for example, if it is hashable or if it is a mapping.
A good example here: https://pymotw.com/2/abc/ | https://pymotw.com/3/abc/
From pymotw:
Forgetting to set the metaclass properly means the concrete implementations do not have their APIs enforced. To make it easier to set up the abstract class properly, a base class is provided that sets the metaclass automatically.
abc_abc_base.py
import abc
class PluginBase(abc.ABC):
@abc.abstractmethod
def load(self, input):
"""Retrieve data from the input source
and return an object.
"""
@abc.abstractmethod
def save(self, output, data):
"""Save the data object to the output."""
class SubclassImplementation(PluginBase):
def load(self, input):
return input.read()
def save(self, output, data):
return output.write(data)
if __name__ == '__main__':
print('Subclass:', issubclass(SubclassImplementation,
PluginBase))
print('Instance:', isinstance(SubclassImplementation(),
PluginBase))
I noticed in a leetcode quesiton answer this -
node.next.random = node.random and node.random.next
Now from my understanding in other languages node.random and node.random.next should return true if both exist and false if they don't, but chatgpt says:
"node.random and node.random.next is an expression using the and logical operator. In Python, the and operator returns the first operand if it is falsy (e.g., None, False, 0, or ""); otherwise, it returns the second operand"
I don't understand this.
In many languages some values evaluate to False. In Python this is False, None, 0, 0.0, [], (), {}, '' and every object, that has a special method which evaluates to False.
In your description you only want to fill a list up to 3 elements. This can be done with:
a, b, c = s + [0,9,1][len(s):]
I don't think this works particularly elegantly in Python - you need to consider what happens when the list is too short and you need to distinguish between None (often used to indicate "doesn't exist") and 0 (which also evaluates to False).
You could use
a = s[0] if (len(s)>0 and s[0] is not None) else 0
It isn't really an elegant idiomatic one-liner though, and you have to remember to write the index of s three times.
Alternatively
# defined once
def get_default(s,idx,default):
return s[idx] if (len(s)>idx and s[idx] is not None) else default
a = get_default(s,0,0)
b = get_default(s,1,9)
...
might do if you're going to be doing this a lot, and always using lists. I think this may just be a case where what works in Javascript doesn't quite work in Python though, and you have to live with that.