I have a class that performs some simple data manipulation, I need three methods: set, add, sub:
class Entry(): # over-simplified but should be enough for the question
def __init__(self, value):
self.set(value)
def set(self, value):
self.value=value
def add(self, value):
self.value += value
def sub(self, value):
self.value -= value
The problem is with the "set" method but defining it as a class method should not clash with the "set()" builtin function.
The Python Style Guide states that argument names of functions and methods should not shadow built-in functions, but it's this the case for method names?
Obviously I could choose another method name, but the question is more generic and valid for other possible method names (i.e. filter, sum, input).
Bottom line: you can't have two things simultaneously with the same name, be it a function, an integer, or any other object in Python. Just use a different name.
To make a method as class method, add @classmethod decorator before the method definition, and add cls as the first parameter to the method. The @classmethod decorator is a built-in function decorator. In Python, we use the @classmethod decorator to declare a method as a class method.
__class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'> After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .
The whole thing about not shadowing builtin names is that you don't want to stop your self from being able to use them, so when your code does this:
x.set(a) #set the value to a
b = set((1,2,3)) #create a set
you can still access the builtin set
so there is no conflict, the only problem is if you wanted to use set
inside the class definition
class Entry():
def __init__(self, value):
self.set(value)
def set(self, value):
self.value=value
possible_values = set((1,2,3,4,5)) #TypeError: set() missing 1 required positional argument: 'value'
Inside the class definition - and there only - is the built in name shadowed, so you have to consider which you would rather settle for: the unlikely scenario where you need to use set
to define a class scope variable and get an error or using a non-intuitive name for your method.
Also note that if you like using method names that make sense to you and also want to use set
in your class definition you can still access it with builtins.set
for python 3 or __builtin__.set
for python 2.
You are fine. You just don't want to overwrite the built-ins if they are a built-in method __init__ __iter__ etc unless you are implementing the functionality expected by those methods.
You are "overwriting" a built in function as a class method, which means you aren't really overwriting anything. This is acceptable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With