Skip to content

Commit 853ec9a

Browse files
author
MomIsBestFriend
committed
Changed x.__class__ to type(x)
1 parent db60ab6 commit 853ec9a

File tree

12 files changed

+45
-50
lines changed

12 files changed

+45
-50
lines changed

pandas/_libs/tslibs/c_timestamp.pyx

+9-12
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ cdef class _Timestamp(datetime):
8787
return PyObject_RichCompareBool(val, other, op)
8888

8989
try:
90-
ots = self.__class__(other)
90+
ots = type(self)(other)
9191
except ValueError:
9292
return self._compare_outside_nanorange(other, op)
9393
else:
@@ -96,7 +96,7 @@ cdef class _Timestamp(datetime):
9696
if ndim != -1:
9797
if ndim == 0:
9898
if is_datetime64_object(other):
99-
other = self.__class__(other)
99+
other = type(self)(other)
100100
elif is_array(other):
101101
# zero-dim array, occurs if try comparison with
102102
# datetime64 scalar on the left hand side
@@ -105,7 +105,7 @@ cdef class _Timestamp(datetime):
105105
# the numpy C api to extract it.
106106
other = cnp.PyArray_ToScalar(cnp.PyArray_DATA(other),
107107
other)
108-
other = self.__class__(other)
108+
other = type(self)(other)
109109
else:
110110
return NotImplemented
111111
elif is_array(other):
@@ -226,8 +226,7 @@ cdef class _Timestamp(datetime):
226226

227227
if is_timedelta64_object(other):
228228
other_int = other.astype('timedelta64[ns]').view('i8')
229-
return self.__class__(self.value + other_int,
230-
tz=self.tzinfo, freq=self.freq)
229+
return type(self)(self.value + other_int, tz=self.tzinfo, freq=self.freq)
231230

232231
elif is_integer_object(other):
233232
maybe_integer_op_deprecated(self)
@@ -238,8 +237,7 @@ cdef class _Timestamp(datetime):
238237
elif self.freq is None:
239238
raise NullFrequencyError(
240239
"Cannot add integral value to Timestamp without freq.")
241-
return self.__class__((self.freq * other).apply(self),
242-
freq=self.freq)
240+
return type(self)((self.freq * other).apply(self), freq=self.freq)
243241

244242
elif PyDelta_Check(other) or hasattr(other, 'delta'):
245243
# delta --> offsets.Tick
@@ -253,8 +251,7 @@ cdef class _Timestamp(datetime):
253251
other.seconds * 1000000 +
254252
other.microseconds) * 1000
255253

256-
result = self.__class__(self.value + nanos,
257-
tz=self.tzinfo, freq=self.freq)
254+
result = type(self)(self.value + nanos, tz=self.tzinfo, freq=self.freq)
258255
return result
259256

260257
elif is_array(other):
@@ -272,7 +269,7 @@ cdef class _Timestamp(datetime):
272269

273270
result = datetime.__add__(self, other)
274271
if PyDateTime_Check(result):
275-
result = self.__class__(result)
272+
result = type(self)(result)
276273
result.nanosecond = self.nanosecond
277274
return result
278275

@@ -304,9 +301,9 @@ cdef class _Timestamp(datetime):
304301
if (PyDateTime_Check(self)
305302
and (PyDateTime_Check(other) or is_datetime64_object(other))):
306303
if isinstance(self, _Timestamp):
307-
other = self.__class__(other)
304+
other = type(self)(other)
308305
else:
309-
self = other.__class__(self)
306+
self = type(other)(self)
310307

311308
# validate tz's
312309
if not tz_compare(self.tzinfo, other.tzinfo):

pandas/core/groupby/base.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def _gotitem(self, key, ndim, subset=None):
4141
except IndexError:
4242
groupby = self._groupby
4343

44-
self = self.__class__(subset, groupby=groupby, parent=self, **kwargs)
44+
self = type(self)(subset, groupby=groupby, parent=self, **kwargs)
4545
self._reset_cache()
4646
if subset.ndim == 2:
4747
if is_scalar(key) and key in subset or is_list_like(key):

pandas/core/indexes/frozen.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -69,13 +69,13 @@ def difference(self, other) -> "FrozenList":
6969

7070
def __getitem__(self, n):
7171
if isinstance(n, slice):
72-
return self.__class__(super().__getitem__(n))
72+
return type(self)(super().__getitem__(n))
7373
return super().__getitem__(n)
7474

7575
def __radd__(self, other):
7676
if isinstance(other, tuple):
7777
other = list(other)
78-
return self.__class__(other + list(self))
78+
return type(self)(other + list(self))
7979

8080
def __eq__(self, other):
8181
if isinstance(other, (tuple, FrozenList)):
@@ -85,7 +85,7 @@ def __eq__(self, other):
8585
__req__ = __eq__
8686

8787
def __mul__(self, other):
88-
return self.__class__(super().__mul__(other))
88+
return type(self)(super().__mul__(other))
8989

9090
__imul__ = __mul__
9191

pandas/core/indexes/range.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -609,27 +609,27 @@ def _union(self, other, sort):
609609
and (start_s - end_o) <= step_s
610610
and (start_o - end_s) <= step_s
611611
):
612-
return self.__class__(start_r, end_r + step_s, step_s)
612+
return type(self)(start_r, end_r + step_s, step_s)
613613
if (
614614
(step_s % 2 == 0)
615615
and (abs(start_s - start_o) <= step_s / 2)
616616
and (abs(end_s - end_o) <= step_s / 2)
617617
):
618-
return self.__class__(start_r, end_r + step_s / 2, step_s / 2)
618+
return type(self)(start_r, end_r + step_s / 2, step_s / 2)
619619
elif step_o % step_s == 0:
620620
if (
621621
(start_o - start_s) % step_s == 0
622622
and (start_o + step_s >= start_s)
623623
and (end_o - step_s <= end_s)
624624
):
625-
return self.__class__(start_r, end_r + step_s, step_s)
625+
return type(self)(start_r, end_r + step_s, step_s)
626626
elif step_s % step_o == 0:
627627
if (
628628
(start_s - start_o) % step_o == 0
629629
and (start_s + step_o >= start_o)
630630
and (end_s - step_o <= end_o)
631631
):
632-
return self.__class__(start_r, end_r + step_o, step_o)
632+
return type(self)(start_r, end_r + step_o, step_o)
633633
return self._int64index._union(other, sort=sort)
634634

635635
@Appender(_index_shared_docs["join"])
@@ -798,7 +798,7 @@ def _evaluate_numeric_binop(self, other):
798798
rstart = op(left.start, right)
799799
rstop = op(left.stop, right)
800800

801-
result = self.__class__(rstart, rstop, rstep, **attrs)
801+
result = type(self)(rstart, rstop, rstep, **attrs)
802802

803803
# for compat with numpy / Int64Index
804804
# even if we can represent as a RangeIndex, return

pandas/core/indexing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ class _NDFrameIndexer(_NDFrameIndexerBase):
105105

106106
def __call__(self, axis=None):
107107
# we need to return a copy of ourselves
108-
new_self = self.__class__(self.name, self.obj)
108+
new_self = type(self)(self.name, self.obj)
109109

110110
if axis is not None:
111111
axis = self.obj._get_axis_number(axis)

pandas/core/internals/managers.py

+9-11
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ def make_empty(self, axes=None):
154154
blocks = np.array([], dtype=self.array_dtype)
155155
else:
156156
blocks = []
157-
return self.__class__(blocks, axes)
157+
return type(self)(blocks, axes)
158158

159159
def __nonzero__(self):
160160
return True
@@ -435,7 +435,7 @@ def apply(
435435

436436
if len(result_blocks) == 0:
437437
return self.make_empty(axes or self.axes)
438-
bm = self.__class__(
438+
bm = type(self)(
439439
result_blocks, axes or self.axes, do_integrity_check=do_integrity_check
440440
)
441441
bm._consolidate_inplace()
@@ -524,7 +524,7 @@ def get_axe(block, qs, axes):
524524
for b in blocks
525525
]
526526

527-
return self.__class__(blocks, new_axes)
527+
return type(self)(blocks, new_axes)
528528

529529
# single block, i.e. ndim == {1}
530530
values = concat_compat([b.values for b in blocks])
@@ -634,7 +634,7 @@ def comp(s, regex=False):
634634
rb = new_rb
635635
result_blocks.extend(rb)
636636

637-
bm = self.__class__(result_blocks, self.axes)
637+
bm = type(self)(result_blocks, self.axes)
638638
bm._consolidate_inplace()
639639
return bm
640640

@@ -729,7 +729,7 @@ def combine(self, blocks, copy=True):
729729
axes = list(self.axes)
730730
axes[0] = self.items.take(indexer)
731731

732-
return self.__class__(new_blocks, axes, do_integrity_check=False)
732+
return type(self)(new_blocks, axes, do_integrity_check=False)
733733

734734
def get_slice(self, slobj, axis=0):
735735
if axis >= self.ndim:
@@ -746,7 +746,7 @@ def get_slice(self, slobj, axis=0):
746746
new_axes = list(self.axes)
747747
new_axes[axis] = new_axes[axis][slobj]
748748

749-
bm = self.__class__(new_blocks, new_axes, do_integrity_check=False)
749+
bm = type(self)(new_blocks, new_axes, do_integrity_check=False)
750750
bm._consolidate_inplace()
751751
return bm
752752

@@ -922,7 +922,7 @@ def consolidate(self):
922922
if self.is_consolidated():
923923
return self
924924

925-
bm = self.__class__(self.blocks, self.axes)
925+
bm = type(self)(self.blocks, self.axes)
926926
bm._is_consolidated = False
927927
bm._consolidate_inplace()
928928
return bm
@@ -1256,7 +1256,7 @@ def reindex_indexer(
12561256

12571257
new_axes = list(self.axes)
12581258
new_axes[axis] = new_axis
1259-
return self.__class__(new_blocks, new_axes)
1259+
return type(self)(new_blocks, new_axes)
12601260

12611261
def _slice_take_blocks_ax0(self, slice_or_indexer, fill_tuple=None):
12621262
"""
@@ -1526,9 +1526,7 @@ def get_slice(self, slobj, axis=0):
15261526
if axis >= self.ndim:
15271527
raise IndexError("Requested axis not found in manager")
15281528

1529-
return self.__class__(
1530-
self._block._slice(slobj), self.index[slobj], fastpath=True
1531-
)
1529+
return type(self)(self._block._slice(slobj), self.index[slobj], fastpath=True)
15321530

15331531
@property
15341532
def index(self):

pandas/core/resample.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -885,7 +885,7 @@ def count(self):
885885
result = self._downsample("count")
886886
if not len(self.ax):
887887
if self._selected_obj.ndim == 1:
888-
result = self._selected_obj.__class__(
888+
result = type(self._selected_obj)(
889889
[], index=result.index, dtype="int64", name=self._selected_obj.name
890890
)
891891
else:

pandas/tests/indexes/common.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -260,8 +260,8 @@ def test_copy_name(self, indices):
260260
if isinstance(indices, MultiIndex):
261261
return
262262

263-
first = indices.__class__(indices, copy=True, name="mario")
264-
second = first.__class__(first, copy=False)
263+
first = type(indices)(indices, copy=True, name="mario")
264+
second = type(first)(first, copy=False)
265265

266266
# Even though "copy=False", we want a new object.
267267
assert first is not second
@@ -677,9 +677,9 @@ def test_hasnans_isnans(self, indices):
677677
values[1] = np.nan
678678

679679
if isinstance(indices, PeriodIndex):
680-
idx = indices.__class__(values, freq=indices.freq)
680+
idx = type(indices)(values, freq=indices.freq)
681681
else:
682-
idx = indices.__class__(values)
682+
idx = type(indices)(values)
683683

684684
expected = np.array([False] * len(idx), dtype=bool)
685685
expected[1] = True
@@ -716,9 +716,9 @@ def test_fillna(self, indices):
716716
values[1] = np.nan
717717

718718
if isinstance(indices, PeriodIndex):
719-
idx = indices.__class__(values, freq=indices.freq)
719+
idx = type(indices)(values, freq=indices.freq)
720720
else:
721-
idx = indices.__class__(values)
721+
idx = type(indices)(values)
722722

723723
expected = np.array([False] * len(idx), dtype=bool)
724724
expected[1] = True

pandas/tests/indexes/multi/test_missing.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,9 @@ def test_fillna(idx):
4242
values[1] = np.nan
4343

4444
if isinstance(index, PeriodIndex):
45-
idx = index.__class__(values, freq=index.freq)
45+
idx = type(index)(values, freq=index.freq)
4646
else:
47-
idx = index.__class__(values)
47+
idx = type(index)(values)
4848

4949
expected = np.array([False] * len(idx), dtype=bool)
5050
expected[1] = True
@@ -115,7 +115,7 @@ def test_hasnans_isnans(idx):
115115
values = index.values
116116
values[1] = np.nan
117117

118-
index = idx.__class__(values)
118+
index = type(idx)(values)
119119

120120
expected = np.array([False] * len(index), dtype=bool)
121121
expected[1] = True

pandas/tests/indexes/period/test_partial_slicing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ def test_range_slice_outofbounds(self):
123123

124124
for idx in [didx, pidx]:
125125
df = DataFrame(dict(units=[100 + i for i in range(10)]), index=idx)
126-
empty = DataFrame(index=idx.__class__([], freq="D"), columns=["units"])
126+
empty = DataFrame(index=type(idx)([], freq="D"), columns=["units"])
127127
empty["units"] = empty["units"].astype("int64")
128128

129129
tm.assert_frame_equal(df["2013/09/01":"2013/09/30"], empty)

pandas/tests/indexes/test_base.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -752,7 +752,7 @@ def test_fancy(self):
752752
@pytest.mark.parametrize("dtype", [np.int_, np.bool_])
753753
def test_empty_fancy(self, index, dtype):
754754
empty_arr = np.array([], dtype=dtype)
755-
empty_index = index.__class__([])
755+
empty_index = type(index)([])
756756

757757
assert index[[]].identical(empty_index)
758758
assert index[empty_arr].identical(empty_index)
@@ -762,7 +762,7 @@ def test_empty_fancy_raises(self, index):
762762
# pd.DatetimeIndex is excluded, because it overrides getitem and should
763763
# be tested separately.
764764
empty_farr = np.array([], dtype=np.float_)
765-
empty_index = index.__class__([])
765+
empty_index = type(index)([])
766766

767767
assert index[[]].identical(empty_index)
768768
# np.ndarray only accepts ndarray of int & bool dtypes, so should Index
@@ -2446,8 +2446,8 @@ def test_copy_name(self):
24462446
# GH12309
24472447
index = self.create_index()
24482448

2449-
first = index.__class__(index, copy=True, name="mario")
2450-
second = first.__class__(first, copy=False)
2449+
first = type(index)(index, copy=True, name="mario")
2450+
second = type(first)(first, copy=False)
24512451

24522452
# Even though "copy=False", we want a new object.
24532453
assert first is not second

pandas/tseries/offsets.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -402,7 +402,7 @@ def rollback(self, dt):
402402
"""
403403
dt = as_timestamp(dt)
404404
if not self.onOffset(dt):
405-
dt = dt - self.__class__(1, normalize=self.normalize, **self.kwds)
405+
dt = dt - type(self)(1, normalize=self.normalize, **self.kwds)
406406
return dt
407407

408408
def rollforward(self, dt):
@@ -416,7 +416,7 @@ def rollforward(self, dt):
416416
"""
417417
dt = as_timestamp(dt)
418418
if not self.onOffset(dt):
419-
dt = dt + self.__class__(1, normalize=self.normalize, **self.kwds)
419+
dt = dt + type(self)(1, normalize=self.normalize, **self.kwds)
420420
return dt
421421

422422
def onOffset(self, dt):

0 commit comments

Comments
 (0)